Node.js
Sequential await
Learn sequential operations with await.
What is sequential await?
When you write several await calls in a row, each one starts only after the previous one finishes. This is called sequential await; the total time is the sum of each step's time.
async function run() {
const a = await loadA();
const b = await loadB();
console.log(a, b);
}
Here loadB starts only after loadA finishes. If loadB depends on loadA's result, this order is required; but if they are independent, you can save time by running them in parallel.
Exercise Your turn: sequential await
Define async function run(). Write const a = await Promise.resolve(5). Write const b = await Promise.resolve(10). Log the sum with console.log(a + b). Call run().
Show example solution
async function run() {
const a = await Promise.resolve(5);
const b = await Promise.resolve(10);
console.log(a + b);
}
run();
When to use sequential?
Sequential await is required when one job's result feeds the next. For example, if you first fetch a user id and then use that id to fetch the profile, the second call needs the first's result; you cannot run them in parallel.
const user = await getUser();
const profile = await getProfile(user.id);
But for independent jobs, parallel execution shortens the total time. The question to ask: Does the second job need the first's result? If yes, sequential; if not, parallel.
Test yourself
-
What happens if you use sequential await for two independent async jobs?
- They run in parallel and finish faster
- They run sequentially and take longer in total
- Both are skipped
- Promise.race starts
Show answer
They run sequentially and take longer in total — Sequential await wastes time on independent jobs.
-
Fill in the blank: sequential await
async function run() {
const a = await Promise.resolve(1);
const b = ____ Promise.resolve(2);
console.log(a + b);
}
Show answer
async function run() {
const a = await Promise.resolve(1);
const b = await Promise.resolve(2);
console.log(a + b);
}
-
Sequential vs parallel
- sequential
- longer total time
- parallel
- shorter total time
- dependent
- needs sequential
Next lesson: Summary - async/await