Back
Close

JavaScript promises, mastering the asynchronous

Magus
450.8K views

Sometimes you have multiple asynchronous tasks to perform and you have to start something when every task is done. When using promises, you can do that with Promise.all. Run the following code to understand the basics of it.

Promise.all example

As you can see, Promise.all returns a promise. The received data is an array containing the data of each given promise. The promise is resvoled when all given promises are resolved.

Beware, Promise.all has a fail-fast behaviour. If a given promise is rejected, the resulting promise of Promise.all will be rejected at this exact moment. It will not wait for the other promises to complete, and the only received data is the error of the rejected request. See the following example for a better understanding.

Promise.all fail-fast behaviour

As you can see, error p4 is displayed. We can't access the result of the other promises. You should only use Promise.all when you need for all of your promises to resolve successfully.

What if you want to start multiple asynchronous jobs at once and you want results even if a job is rejected? Just use catch. See the following example.

Promise.all with catch

In this example, we don't give the promises directly to Promise.all. We give the result of p.catch (this is an auto-resolved promise) so Promise.all won't stop. In this case, however, you have to test the received data yourself to check for errors.

Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io