Call async/await Functions in Parallel

Better Stack Team
Updated on April 4, 2024

To call async/await functions in parallel in JavaScript, you can use Promise.all to concurrently execute multiple asynchronous functions and wait for all of them to complete. Here's an example:

 
// Assume you have two asynchronous functions that return promises
async function asyncFunction1() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Async function 1');
      resolve('Result from async function 1');
    }, 1000);
  });
}

async function asyncFunction2() {
  return new Promise((resolve) => {
    setTimeout(() => {
      console.log('Async function 2');
      resolve('Result from async function 2');
    }, 1500);
  });
}

// Call both functions in parallel using Promise.all
async function executeParallelFunctions() {
  try {
    const [result1, result2] = await Promise.all([asyncFunction1(), asyncFunction2()]);

    console.log('Results:', result1, result2);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Invoke the function
executeParallelFunctions();

In this example:

  1. asyncFunction1 and asyncFunction2 are two asynchronous functions that return promises.
  2. The executeParallelFunctions function uses Promise.all to call both functions concurrently.
  3. The await Promise.all([...]) statement waits for all promises to resolve and returns an array of results.
  4. The results are then logged to the console.

This approach is effective for running multiple asynchronous functions in parallel and is especially useful when the functions are independent of each other and don't rely on the results of the others.

Keep in mind that if one of the promises is rejected, Promise.all will reject with the reason of the first promise that was rejected. Ensure proper error handling as demonstrated in the example.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.