Working with arrays of promises in JavaScript

Now we will analyze two useful methods that allow you to work with arrays of promises. The Promise.all method allows the code to be executed after all the promises passed to it as an array. The Promise.race method waits for the first promise from the array to be fulfilled, discarding the rest.

Both methods return a new promise as their result. For the Promise.all method, the result of this promise will be an array of the results of all passed promises (the results order corresponds to the order of the promises in the array), and for Promise.race, the result of the first fulfilled promise.

Let's see in practice. Let's have an array of promises:

let promises = [ new Promise(resolve => setTimeout(() => resolve(1), 1000)), new Promise(resolve => setTimeout(() => resolve(2), 2000)), new Promise(resolve => setTimeout(() => resolve(3), 3000)), ];

Let's use Promise.all to wait until all promises from our array are fulfilled:

Promise.all(promises).then(function(res) { console.log(res); // shows [1, 2, 3] - results of all the promises });

And now, using Promise.race, we will wait for the first of the promises to be fulfilled:

Promise.race(promises).then(function(res) { console.log(res); // shows 1 - the result of the first fulfilled promise });

If at least one of the promises in the array is rejected, then the promise with the result will immediately go into the rejected state. Therefore, an exception that has arisen can be caught in the usual way you have already studied, for example, through catch:

Promise.all(promises).then(function(res) { console.log(res); }).catch(function(err) { console.log(err); });

Make a function that returns a promise with a random delay between 1 and 10 seconds inside it. Let the result of the promise return this delay. With a loop and your function, fill the array with 10 promises.

Using the array of promises from the previous task, make sure that the result of the first triggered promise is displayed in the console.

Using the array of promises from the previous task, print the sum of the results of all promises to the console.

enru