6 Advanced Applications of Function Types

 

This chapter covers

  • A simplified decorator pattern
  • Implementing a resumable counter
  • Ways to handle long-running operations
  • Writing clean asynchronous code using promises and async/await

In the previous chapter 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 which 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 go over a quick refresher). We’ll introduce the concept of a closure and see how we can use it to implement a simple counter. We’ll then look at another alternative 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.1.1 A Functional Decorator

6.1.2 Decorator Implementations

6.1.3 Closures

6.1.4 Exercises

6.2       Implementing a Counter

6.2.1 An Object-Oriented Counter

6.2.2 A Functional Counter

6.2.3 A Resumable Counter

6.2.4 Counter Implementations Recap

6.2.5 Exercises

6.3       Executing Long-Running Operations Asynchronously

6.3.1 Synchronous Execution

6.3.2 Asynchronous Execution: Callbacks

6.3.3 Asynchronous Execution Models

6.3.4 Asynchronous Functions Recap

6.3.5 Exercises

6.4       Simplifying Asynchronous Code

6.4.1 Chaining Promises

6.4.2 Creating Promises

6.4.3 More About Promises

6.4.4 async/await

6.4.5 Clean Asynchronous Code Recap

6.4.6 Exercises

6.5       Summary

6.6       Answers to Exercises

sitemap