Sequential vs parallel
For-await in order
A plain for loop with await runs tasks in strict order. Each iteration waits for the prior one to settle. This is the safest shape when order matters or the server allows only one call at a time. The program calls inOrder with three ids, so the users print one after another in list order.
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function inOrder(ids: number[]): Promise<void> { for (const id of ids) { const u = await fetchOne(id); console.log(u); } } inOrder([1, 2, 3]);
user 1
user 2
user 3
Parallel with map+all
Map plus all starts every task without waiting between launches. The total wait is close to the slowest single task. Use this shape for independent calls that can safely overlap. The fetchOne helper is repeated here, so the block runs on its own. Promise.all keeps the order of the list, so the users print in list order even though every call starts at once.
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function allAtOnce(ids: number[]): Promise<void> { const users: string[] = await Promise.all(ids.map(fetchOne)); console.log(users.length); for (const u of users) { console.log(u); } } allAtOnce([1, 2, 3]);
3
user 1
user 2
user 3
Limit concurrency simply
Full parallel can flood a server, so process inputs in small batches. Slice the list into chunks and await all for one chunk at a time. Batch size two or five covers most cases without extra libraries. The fetchOne helper is repeated here, and each batch prints its users on one line, so the output shows where one batch ends and the next begins.
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function batched(ids: number[]): Promise<void> { const size = 2; for (let i = 0; i < ids.length; i += size) { const chunk = ids.slice(i, i + size); const users: string[] = await Promise.all(chunk.map(fetchOne)); console.log(users.join(", ")); } } batched([1, 2, 3]);
user 1, user 2
user 3
Choose by dependency
Choose serial when one step needs the value from the prior step. Choose parallel when inputs are ready up front and do not interact. When in doubt, start serial for clarity and switch to batches once timing proves the need. The fetchOne, inOrder and allAtOnce helpers are repeated here, and the program runs both shapes in turn, so the parallel pair prints before the serial pair.
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function inOrder(ids: number[]): Promise<void> { for (const id of ids) { const u = await fetchOne(id); console.log(u); } } async function allAtOnce(ids: number[]): Promise<void> { const users: string[] = await Promise.all(ids.map(fetchOne)); console.log(users.length); for (const u of users) { console.log(u); } } async function choose(ids: number[], parallel: boolean): Promise<void> { if (parallel) { await allAtOnce(ids); } else { await inOrder(ids); } } async function main(): Promise<void> { await choose([1, 2], true); await choose([3, 4], false); } main();
2
user 1
user 2
user 3
user 4
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
In a for loop with await, when does the next iteration start?
Answer
After the promise of the current iteration settles
The await pauses the loop body, so the next id is not taken until the current call has finished.
-
What does map plus Promise.all do with the start of the tasks?
Answer
It starts every task without waiting between launches
Every call is launched first and the results are awaited together, so the total wait is close to the slowest single task.
-
Why process a long list in small batches?
Answer
Full parallel can flood a server with too many calls at once
A batch caps how many calls are in flight, which protects the server without the code of a full task pool.
-
When is the serial shape the right choice?
Answer
When one step needs the value that the prior step produced
A dependent step cannot start before the value it needs exists, so the calls must run one after another.
-
What does this program print?
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function inOrder(ids: number[]): Promise<void> { for (const id of ids) { const u = await fetchOne(id); console.log(u); } } inOrder([3, 1, 2]);Answer
user 3 / user 1 / user 2
The loop walks the list as it is given and never sorts it, so the ids print in the order of the array.
-
What does this program print?
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function allAtOnce(ids: number[]): Promise<void> { const users: string[] = await Promise.all(ids.map(fetchOne)); console.log(users.join(", ")); } allAtOnce([2, 1]);Answer
user 2, user 1
Promise.all keeps the order of the input list, so the results arrive in the order of the ids, not in the order they finish.
-
What does this program print?
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function batched(ids: number[]): Promise<void> { const size = 2; for (let i = 0; i < ids.length; i += size) { const chunk = ids.slice(i, i + size); const users: string[] = await Promise.all(chunk.map(fetchOne)); console.log(users.join(", ")); } } batched([1, 2, 3]);Answer
user 1, user 2 / user 3
The first batch takes ids 1 and 2, and the second batch takes the remaining id 3.
-
What does the compiler say about this program?
async function fetchOne(id: number): Promise<string> { return "user " + id; } function allAtOnce(ids: number[]): number { const users: string[] = await Promise.all(ids.map(fetchOne)); return users.length; } console.log(allAtOnce([1, 2]));Answer
error TS1308: 'await' expressions are only allowed within async functions and at the top levels of modules.
An await may appear only in an async function or at the top level of a module, so allAtOnce must be declared async.
-
Why does forEach with an async callback not run the tasks in order?
Answer
It throws away the promises the callback returns, so nothing waits for them
forEach ignores the returned promise of each callback, so the calls overlap and the loop ends before the work does.
-
What does this program print?
async function fetchOne(id: number): Promise<string> { return "user " + id; } async function allAtOnce(ids: number[]): Promise<void> { const users = ids.map(fetchOne); console.log(users.length); } allAtOnce([1, 2, 3]);Answer
3
Map without Promise.all gives an array of promises, and its length is still the number of ids, so only the count prints.
Article author: Arthur Isaev