Sometimes you want tasks to run one after another, and sometimes you want them to run at the same time to save time.
0
0
Sequential vs parallel async execution in Node.js
Introduction
When you need to wait for one task to finish before starting the next.
When tasks are independent and can run at the same time to finish faster.
When you want to avoid blocking the program while waiting for slow tasks.
When you want to improve performance by running multiple tasks together.
When order of task completion matters for your program logic.
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
Runs fetchUser first, then fetchPosts after user is ready.
Node.js
async function fetchSequential() { const user = await fetchUser(); const posts = await fetchPosts(user.id); return posts; }
Starts fetchUser and fetchPosts at the same time, waits for both.
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);
})();OutputSuccess
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.