Open In App

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:



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.




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()

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




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:

Approach 2: using Promise.allSettled()

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




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:

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

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




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:


Article Tags :