JavaScript Promises

Using Promises

Say we have an API client with three methods, getItem(), updateItem(), and deleteItem(), each of which returns a Promise. There are only two functions you need to worry about: then() and catch().

Each call to then() creates another step in the Promise chain, and if there’s an error at any point in the chain, the next catch() block will be triggered. Both then() and catch() can either return a raw value or a new Promise, and the result will be passed to the next then() in the chain.

Convert callback to Promises

If a function doesn’t return a Promise but rather a callback, like Node’s fs.readile function,

https://nodejs.org/api/fs.html#fs_fs_readfile_path_options_callback

then you can convert the call to a Promise as follows. The new function, called readFilePromise, converts the original function, called readFile, into a Promise.

To use the new promise function, do this.

To create Promises out of ordinary values, use Promise.resolve() and Promise.reject().

If you have a function that needs to return a Promise, like fs.readFile, but handle certain cases synchronously, you can use Promise.resolve() and Promise.reject() to create Promises out of ordinary values, like this.

Running concurrently

Promise.all is a convenient method for running an array of Promises concurrently, i.e. all at the same time. For instance, say we have a list of files we want to read from disk. Using the readFilePromise function we created above, it would look like this:

Here’s another example

And another example (from Kyle Simpson)

In the example above, we can use the new Promisified function in the chain as follows. We can also create a new Promise that returns a Promise of an ordinary value to keep the chain going.