8 Functions for the future: promises and generators
This chapter covers
- Handling asynchronous tasks with promises
- Using the async/await syntax instead of callbacks
- Continuing function execution with generators
In the previous three chapters, we focused on functions, specifically on how to define functions and how to use them to great effect. In some cases, we’ve passed a function as a callback to be invoked when some event occurs in the future. Callbacks have always been a part of JavaScript and remain a common pattern. However, they aren’t the only way to deal with future events. One of the most important features in modern JavaScript is the promise, an object representation of an event.
As we’ll soon see, promises and the associated async and await keywords have become the preferred way of dealing with events in a wide variety of situations. We’ll also look at generators, a lesser-used JavaScript feature that can provide a convenient alternative to loops, both synchronous and asynchronous.
8.1 The power of promises
A promise is an object that represents the outcome of an operation. Since their introduction in ES2015, promises have become a ubiquitous part of the JavaScript language, beloved by developers for their convenience and flexibility.
Promises are often touted as an alternative to callbacks, and we’ll soon see why. But in its purest form, a promise is just a way of moving a callback. Let’s start with a simple example: