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.
Promise.all for parallel execution in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
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.
const p1 = Promise.resolve(1); const p2 = Promise.resolve(2); Promise.all([p1, p2]).then(results => console.log(results));
const p1 = Promise.resolve('a'); const p2 = new Promise((res) => setTimeout(() => res('b'), 100)); Promise.all([p1, p2]).then(results => console.log(results));
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));
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.
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();
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.
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.
Practice
Promise.all do in Node.js?Solution
Step 1: Understand Promise.all behavior
Promise.all runs all promises at the same time (in parallel) and waits until all finish.Step 2: Check result order and completion
It returns results in the order of the promises given, not random or sequentially one by one.Final Answer:
Runs multiple promises in parallel and waits for all to complete -> Option CQuick Check:
Promise.all = parallel run + wait all [OK]
- Thinking Promise.all runs promises sequentially
- Believing Promise.all returns results in random order
- Assuming Promise.all ignores failed promises
Promise.all with an array of promises named promises?Solution
Step 1: Check Promise.all usage
Promise.all is called as a function with an array of promises as argument.Step 2: Verify chaining with then()
To get results, use .then() after Promise.all to handle resolved values.Final Answer:
Promise.all(promises).then(results => console.log(results)); -> Option AQuick Check:
Correct syntax = Promise.all(array).then() [OK]
- Using Promise.all.then(promises) instead of Promise.all(promises).then()
- Using catch() to handle results instead of errors
- Using finally() to get results instead of then()
const p1 = Promise.resolve(1); const p2 = Promise.resolve(2); const p3 = Promise.resolve(3); Promise.all([p1, p2, p3]).then(results => console.log(results));
Solution
Step 1: Understand resolved promises
p1, p2, p3 are promises resolved immediately with values 1, 2, and 3.Step 2: Promise.all returns array of results in input order
Promise.all waits for all to resolve and returns results in the same order as input array.Final Answer:
[1, 2, 3] -> Option BQuick Check:
Promise.all results order = input order [OK]
- Assuming results order depends on resolution speed
- Expecting reversed or random order
- Thinking Promise.all returns undefined values
const p1 = Promise.resolve('A');
const p2 = Promise.reject('Error');
Promise.all([p1, p2])
.then(results => console.log('Results:', results))
.catch(error => console.log('Caught:', error));Solution
Step 1: Check behavior of Promise.all with rejected promises
If any promise rejects, Promise.all immediately rejects with that error.Step 2: Analyze catch and then blocks
Since p2 rejects, the catch block runs with the error message 'Error'. The then block does not run.Final Answer:
The catch block will run with 'Error' because p2 rejects -> Option AQuick Check:
Promise.all rejects if any promise rejects [OK]
- Thinking Promise.all ignores rejected promises
- Expecting then block to run with partial results
- Believing Promise.reject causes syntax error here
Promise.all to achieve this?const fetch1 = () => fetch('https://api1.example.com/data').then(res => res.json());
const fetch2 = () => fetch('https://api2.example.com/data').then(res => res.json());
const fetch3 = () => fetch('https://api3.example.com/data').then(res => res.json());
// Which code snippet correctly waits for all fetches and handles errors?Solution
Step 1: Check how to call fetch functions
fetch1, fetch2, fetch3 are functions returning promises, so call them with () to get promises.Step 2: Verify Promise.all usage and error handling
Pass an array of promises to Promise.all, then use .then() to handle results and .catch() for errors.Final Answer:
Promise.all([fetch1(), fetch2(), fetch3()]) .then(results => console.log('All data:', results)) .catch(error => console.error('Fetch failed:', error)); -> Option DQuick Check:
Call functions to get promises, pass array to Promise.all [OK]
- Passing functions instead of calling them
- Passing multiple arguments instead of an array
- Swapping console.log and console.error in then/catch
