You are viewing the preview version of this book
Click here for the full version.

Promises

So far we've discussed how to write Promise-producing async functions and how to wait for a Promise to have a value. But how to create Promises in cases where there are no existing Promises to build on?

To know this, we need to discuss how asynchronicity works in JavaScript and how to construct Promises from callbacks.

Callbacks

Async results come in the form of callbacks. These are like the parameter of the then() function in Promises but are called when a particular event happens. For example, the simplest callback is the setTimeout call that waits a given number of milliseconds then invokes the argument function:

setTimeout(() => {
  // 1s later
}, 1000);

This pattern of using callbacks is everywhere in JavaScript.

The gapi, the library to use Google services, needs a callback when it loads a client library:

gapi.load("client:auth2", () => {
  // auth2 client loaded
});

Similarly, event listeners, such as a click handler, calls a function when the event happened:

const button = document.querySelector("#button");

button.addEventListener("click", () => {
  // button is clicked
}, {once: true})

The problem with callbacks is that we are back to square one as instead of having a flat structure we have nesting again.

Fortunately, there is a simple way to convert callbacks to Promises and then use them with await.

Event listeners and Promises

Eagle-eyed readers might have spotted the {once: true} part in the last example. Event listeners are inherently different than async functions as they represent multiple events instead of a single result value. Because of this, you can not replace them with Promises.

The exception is when there is exactly one event, as in the above example. In a sense, it works similarly to the timeout or the gapi load function, as the callback is invoked when the event happens.

The Promise constructor

There is more, but you've reached the end of this preview
Read this and all other chapters in full and get lifetime access to:
  • all future updates
  • full web-based access
  • PDF and Epub versions