How to usePromise.all() in Javascript

  • In this approach, we will use Promise.all() method which takes all promises in a single array as its input.
  • As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together.
  • The values in the newly returned single promise will be in a sequential manner (that it is one after the other).
  • The output which will be returned is in the form of an array that will consist of the values which are either resolved or rejected by the other two promises.

Example: Let us see the following code which illustrates the above approach:

Javascript




let promise1 = new Promise((resolve, reject) => {
    resolve("Hello! ");
});
 
let promise2 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("w3wiki");
    }, 1000);
});
 
promise1.then((result1) => {
    console.log(result1);
    return promise2;
}).then((result2) => {
    console.log(result2);
});


Output:

How to execute multiple promises sequentially in JavaScript ?

In this article, we will try to understand how we could easily execute multiple promises in a sequential manner (one after the other) with several techniques or methods provided by JavaScript.

Following are certain approaches through which we could easily execute multiple promises in a sequential manner:

Table of Content

  • Using Promise.all()
  • Using Promise.allSettled()
  • Using for-of-loop along with the async-await

Let us first quickly understand how we may create a promise by using the following syntax provided by JavaScript.

Syntax:

let promise = new Promise((resolve, reject) => resolve(10));

By using the above syntax we could create our promise successfully by either resolving it (having the resolved state) or rejecting it (having the rejected state).

Example: In this example, we will create a simple promise just to see how it works or how it gets executed.

Javascript




let promise = new Promise((resolve, reject) => {
    resolve("w3wiki");
});
promise.then(result => console.log(result));


Output:

w3wiki

Note: Now that we have understood how to create a promise let us quickly see and visualize how we could execute multiple promises in a sequential manner.

Similar Reads

Approach 1: Using Promise.all()

...

Approach 2: using Promise.allSettled()

In this approach, we will use Promise.all() method which takes all promises in a single array as its input. As a result, this method executes all the promises in itself and returns a new single promise in which the values of all the other promises are combined together. The values in the newly returned single promise will be in a sequential manner (that it is one after the other). The output which will be returned is in the form of an array that will consist of the values which are either resolved or rejected by the other two promises....

Approach 3: Using for-of-loop along with the async-await

...