Open In App

How to execute multiple promises sequentially in JavaScript ?

Last Updated : 15 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

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("GeeksforGeeks");
});
promise.then(result => console.log(result));


Output:

GeeksforGeeks

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.

Approach 1: Using Promise.all()

  • 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("GeeksforGeeks");
    }, 1000);
});
 
promise1.then((result1) => {
    console.log(result1);
    return promise2;
}).then((result2) => {
    console.log(result2);
});


Output:

javscrip4Approach 2: using Promise.allSettled()

  • In this approach, we will use Promise.allSettled() which will be executed in a quite similar manner as Promise.all() method executed by taking promises as input in the single array and executing them sequentially.
  • There is a slight difference which is that this Promise.allSettled() method returns an array of objects in which along with the state of each promise (either fulfilled or rejected), the value of each promise is also there.

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("GeeksforGeeks");
    }, 1000);
});
 
const promises = [promise1, promise2];
 
const executePromisesSequentially = async () => {
    const result =
        await promises.reduce(async (
            accumulator, currentPromise) => {
        const results = await accumulator;
        return [...results, await currentPromise];
    }, Promise.resolve([]));
 
    console.log(result);
};
 
executePromisesSequentially();


Output:

javscrip5

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

  • In this approach, we will use for-of-loop along with the async-await methods.
  • We will run the loop over the array of promises, further making an async function, and thus await the result into the resultant promise along with the try-catch block and thus print the result over the browser’s console.

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("GeeksforGeeks");
    }, 1000);
});
 
let promiseExecution = async () => {
    for (let promise of [promise1, promise2]) {
        try {
            const message = await promise;
            console.log(message);
        } catch (error) {
            console.log(error.message);
        }
    }
};
promiseExecution();


Output:

javscrip4



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads