0
0
NodejsHow-ToBeginner · 3 min read

How to Use Promise.all in Node.js for Parallel Async Tasks

In Node.js, Promise.all takes an array of promises and returns a new promise that resolves when all input promises resolve, or rejects if any promise rejects. It lets you run multiple asynchronous tasks in parallel and get all their results together.
📐

Syntax

The Promise.all method accepts an array (or iterable) of promises and returns a single promise. This returned promise:

  • Resolves with an array of results when all promises succeed.
  • Rejects immediately if any promise fails, with the first rejection reason.

Use it to wait for multiple async operations to finish together.

javascript
Promise.all(iterableOfPromises)
  .then(results => {
    // results is an array of resolved values
  })
  .catch(error => {
    // error is the first rejection reason
  });
💻

Example

This example shows how to run three asynchronous tasks in parallel using Promise.all. It waits for all to finish and then logs their results.

javascript
const fetchData = (id) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`Data for ID: ${id}`);
    }, 1000 * id);
  });
};

async function runAll() {
  try {
    const results = await Promise.all([
      fetchData(1),
      fetchData(2),
      fetchData(3)
    ]);
    console.log('All results:', results);
  } catch (error) {
    console.error('Error:', error);
  }
}

runAll();
Output
All results: [ 'Data for ID: 1', 'Data for ID: 2', 'Data for ID: 3' ]
⚠️

Common Pitfalls

Common mistakes when using Promise.all include:

  • Passing non-promise values without wrapping them as promises (though Promise.all accepts them and treats them as resolved).
  • Not handling rejection properly, which causes the entire Promise.all to reject immediately.
  • Expecting Promise.all to wait for all promises even if one rejects (it stops at first rejection).

Always use try/catch or .catch() to handle errors.

javascript
const p1 = Promise.resolve('Success');
const p2 = Promise.reject(new Error('Failure'));

Promise.all([p1, p2])
  .then(results => {
    console.log('This will not run');
  })
  .catch(error => {
    console.error('Caught error:', error); // Outputs: Caught error: Error: Failure
  });
Output
Caught error: Error: Failure
📊

Quick Reference

Tips for using Promise.all:

  • Use it to run multiple async tasks in parallel.
  • It resolves with an array of results in the same order as input promises.
  • If any promise rejects, it rejects immediately with that error.
  • Wrap non-promise values if needed, but Promise.all handles them as resolved.
  • Use try/catch or .catch() to handle errors gracefully.

Key Takeaways

Promise.all runs multiple promises in parallel and waits for all to resolve.
It returns a single promise that resolves with an array of results or rejects on the first error.
Always handle errors with try/catch or .catch to avoid unhandled rejections.
The order of results matches the order of input promises, regardless of completion order.
Non-promise values in the input array are treated as resolved promises.