Chapter 6. Advanced applications of function types

 

This chapter covers

  • Using a simplified decorator pattern
  • Implementing a resumable counter
  • Handling long-running operations
  • Writing clean asynchronous code by using promises and async/await

In chapter 5, we covered the basics of function types and scenarios enabled by the ability to treat functions like other values by passing them as arguments and returning them as results. We also looked at some powerful abstractions that implement common data processing patterns: map(), filter(), and reduce().

In this chapter, we’ll continue our discussion of function types with some more advanced applications. We’ll start by looking at the decorator pattern, its by-the-book implementation, and an alternative implementation. (Again, don’t worry if you forgot it; we’ll have a quick refresher.) We’ll introduce the concept of a closure and see how we can use it to implement a simple counter. Then we’ll look at another way to implement a counter, this time with a generator: a function that yields multiple results.

Next, we’ll talk about asynchronous operations. We’ll go over the two main asynchronous execution models—threads and event loops—and look at how we can sequence several long-running operations. We’ll start with callbacks; then we’ll look at promises, and finally, we’ll cover the async/await syntax provided nowadays by most mainstream programming languages.

6.1. A simple decorator pattern

6.2. Implementing a counter

6.3. Executing long-running operations asynchronously

6.4. Simplifying asynchronous code

Summary

Answers to exercises

sitemap