Sometimes you want tasks to run one after another, and sometimes you want them to run at the same time to save time.
Sequential vs parallel async execution in Node.js
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Node.js
async function sequential() { const result1 = await task1(); const result2 = await task2(); return [result1, result2]; } async function parallel() { const promise1 = task1(); const promise2 = task2(); const results = await Promise.all([promise1, promise2]); return results; }
await pauses the function until the promise resolves.
Promise.all runs promises at the same time and waits for all to finish.
Examples
Node.js
async function fetchSequential() { const user = await fetchUser(); const posts = await fetchPosts(user.id); return posts; }
Node.js
async function fetchParallel() { const userPromise = fetchUser(); const postsPromise = fetchPosts(1); const [user, posts] = await Promise.all([userPromise, postsPromise]); return { user, posts }; }
Sample Program
This program shows two tasks that take different times. It runs them first one after another, then both at the same time. The console times show how long each way takes.
Node.js
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function task1() {
await wait(1000);
return 'Task 1 done';
}
async function task2() {
await wait(500);
return 'Task 2 done';
}
async function runSequential() {
console.time('Sequential');
const result1 = await task1();
const result2 = await task2();
console.timeEnd('Sequential');
return [result1, result2];
}
async function runParallel() {
console.time('Parallel');
const promise1 = task1();
const promise2 = task2();
const results = await Promise.all([promise1, promise2]);
console.timeEnd('Parallel');
return results;
}
(async () => {
const seqResults = await runSequential();
console.log('Sequential results:', seqResults);
const parResults = await runParallel();
console.log('Parallel results:', parResults);
})();Important Notes
Sequential execution waits for each task to finish before starting the next.
Parallel execution starts all tasks at once and waits for all to finish.
Use parallel when tasks do not depend on each other to save time.
Summary
Sequential async runs tasks one by one, waiting for each.
Parallel async runs tasks together, finishing faster if independent.
Choose the method based on task dependencies and performance needs.
Practice
1. What is the main difference between sequential and parallel async execution in Node.js?
easy
Solution
Step 1: Understand sequential async execution
Sequential async means tasks run one after another, waiting for each to complete before starting the next.Step 2: Understand parallel async execution
Parallel async means tasks run at the same time, without waiting for others to finish first.Final Answer:
Sequential async waits for each task to finish before starting the next, while parallel async runs tasks at the same time. -> Option BQuick Check:
Sequential vs parallel async = D [OK]
Hint: Sequential waits, parallel runs together [OK]
Common Mistakes:
- Confusing which runs tasks one by one
- Thinking parallel always uses callbacks
- Assuming sequential is always faster
2. Which of the following is the correct syntax to run two async functions
task1() and task2() in parallel using Promise.all?easy
Solution
Step 1: Recall Promise.all syntax
Promise.all takes an array of promises and waits for all to complete in parallel.Step 2: Check correct usage
The correct syntax isawait Promise.all([task1(), task2()])to run both tasks in parallel and wait for both.Final Answer:
await Promise.all([task1(), task2()]); -> Option AQuick Check:
Promise.all needs array of promises [OK]
Hint: Use Promise.all with array for parallel [OK]
Common Mistakes:
- Missing array brackets in Promise.all
- Awaiting tasks one by one (sequential)
- Calling then() incorrectly without chaining
3. Consider this code snippet:
What will be the order of execution and output behavior?
async function run() {
const result1 = await task1();
const result2 = await task2();
return [result1, result2];
}
run().then(console.log);What will be the order of execution and output behavior?
medium
Solution
Step 1: Analyze await usage
Each await pauses execution until the promise resolves, so task1 finishes before task2 starts.Step 2: Understand output array
Both results are collected in order into an array and returned, so output is [result1, result2].Final Answer:
task1 runs first, then task2 starts after task1 finishes; output is an array of both results. -> Option DQuick Check:
Sequential await = B [OK]
Hint: Await pauses; tasks run one after another [OK]
Common Mistakes:
- Assuming tasks run in parallel with sequential await
- Thinking output order is reversed
- Believing output contains only one result
4. Identify the error in this code snippet intended to run two async tasks in parallel:
async function run() {
const results = await Promise.all(task1(), task2());
console.log(results);
}medium
Solution
Step 1: Check Promise.all argument
Promise.all expects a single array of promises, but here two arguments are passed separately.Step 2: Correct usage
It should bePromise.all([task1(), task2()])with square brackets to group promises.Final Answer:
Promise.all requires an array of promises, but here arguments are passed separately. -> Option AQuick Check:
Promise.all needs array argument [OK]
Hint: Promise.all needs array, not separate args [OK]
Common Mistakes:
- Passing promises as separate arguments
- Thinking await can't be used with Promise.all
- Misunderstanding console.log capabilities
5. You have three independent async tasks:
taskA(), taskB(), and taskC(). You want to run taskA and taskB in parallel, then run taskC only after both finish. Which code correctly implements this?hard
Solution
Step 1: Run taskA and taskB in parallel
Usingawait Promise.all([taskA(), taskB()])runs both tasks at the same time and waits for both to finish.Step 2: Run taskC after both finish
After awaiting both,await taskC()runs taskC sequentially, ensuring it starts only after taskA and taskB complete.Final Answer:
const [a, b] = await Promise.all([taskA(), taskB()]); const c = await taskC(); -> Option CQuick Check:
Parallel first, then sequential = A [OK]
Hint: Use Promise.all for parallel, then await next task [OK]
Common Mistakes:
- Running all tasks in parallel ignoring order
- Running tasks sequentially without parallelism
- Starting taskC before taskA and taskB finish
