Open In App

How to wait for multiple Promises in JavaScript ?

In this article, we will discuss how to wait for multiple promises in JavaScript.

A Promise is basically an object that represents the completion (or failure) of an asynchronous operation along with its result. A promise has 3 types of states and based upon these states, the promise executes the results.



Table of Content

Promise. all( )

Promise. all() in JavaScript handles multiple promises concurrently, resolving when all promises in an array resolve, or rejecting if any of them fail, streamlining asynchronous operations.



Syntax

Promise.all([
    // Array of promises
    promise1,
    promise2,
])
    .then((results) => {
        // Handle the resolved results
    })
    .catch((error) => {
        
        // Handle errors on promise rejection.
    });

Approach

Example: This example illustrates how to wait for multiple promises by using Promise.all( ) function in JavaScript.




// Array of promises
  
const promises = [
    new Promise((resolve) =>
        setTimeout(() => resolve("first"), 2000)),
    new Promise((resolve) =>
        setTimeout(() => resolve("second"), 2500)),
    new Promise((resolve) =>
        setTimeout(() => resolve("third"), 1000)),
];
  
// Use Promise.all to wait 
// for all promises to resolve
  
Promise.all(promises)
    .then((result) => {
        console.log("All promises have been resolved ", result);
  
        // Handle the resolved values here
    })
    .catch((error) => {
        console.error(
            "At least any one promise is rejected:", error);
    });

Output:

All promises have been resolved  [ 'first', 'second', 'third' ]

Async/await

Async/await is a JavaScript feature used to simplify asynchronous programming by allowing code to pause and resume using the await keyword within functions marked as async, enhancing readability and maintainability.

Syntax

async function fetchData() {
    const [res1, res2] = await Promise.all([
        fetch(' '),
        fetch(' '),
    ]);
    
    // Perform operations on result received 
}
fetchData();

Approach

Example: This is the code showing how to wait for multiple promises by using async await in JavaScript.




async function fetchData() {
  
    // Fetching the users profile 
    // and follower data in parallel
  
    const [title1, title2] =
        await Promise.all([
            (await fetch('https://...example.com/'))
                .json(),
            (await fetch('https://...example.com/'))
                .json(),
        ]);
  
    alert(`First title is 
           ${title1.title} and Second title is 
           ${title2.title}`);
}
fetchData();

Output:

Output

Note: For this example, you may use any random Public API for the desired output.


Article Tags :