Promise.all helps you run many tasks at the same time and wait for all of them to finish. This makes your program faster and more efficient.
0
0
Promise.all for parallel execution in Node.js
Introduction
When you want to fetch data from multiple websites at once.
When you need to read several files from disk in parallel.
When you want to run multiple independent calculations together.
When you want to load several resources like images or data simultaneously.
When you want to wait for many asynchronous tasks to complete before continuing.
Syntax
Node.js
Promise.all([promise1, promise2, promise3])
.then(results => {
// use results array here
})
.catch(error => {
// handle any error from promises
});Promise.all takes an array of promises and returns a new promise.
The new promise resolves when all promises succeed, or rejects if any promise fails.
Examples
This example runs two promises that immediately resolve and logs [1, 2].
Node.js
const p1 = Promise.resolve(1); const p2 = Promise.resolve(2); Promise.all([p1, p2]).then(results => console.log(results));
This waits for both promises, including one delayed by 100ms, then logs ['a', 'b'].
Node.js
const p1 = Promise.resolve('a'); const p2 = new Promise((res) => setTimeout(() => res('b'), 100)); Promise.all([p1, p2]).then(results => console.log(results));
If any promise rejects, Promise.all rejects immediately with that error.
Node.js
const p1 = Promise.resolve('ok'); const p2 = Promise.reject('error'); Promise.all([p1, p2]) .then(results => console.log(results)) .catch(error => console.log('Failed:', error));
Sample Program
This program simulates fetching three pieces of data in parallel with different delays. Promise.all waits for all to finish and then logs the results together.
Node.js
import { setTimeout } from 'node:timers/promises'; async function fetchData(id) { await setTimeout(100 * id); // simulate delay return `data${id}`; } async function run() { const promises = [fetchData(1), fetchData(2), fetchData(3)]; try { const results = await Promise.all(promises); console.log('All data:', results); } catch (error) { console.log('Error:', error); } } run();
OutputSuccess
Important Notes
Promise.all preserves the order of results matching the order of input promises.
If any promise rejects, Promise.all stops waiting and rejects immediately.
Use Promise.all when tasks are independent and can run at the same time.
Summary
Promise.all runs many promises at once and waits for all to finish.
It returns results in the same order as the promises you gave it.
If one promise fails, the whole Promise.all fails right away.