Advanced · 12 min
Sequence asynchronous work
Choose sequential or parallel execution based on dependencies.
Wait between dependent steps
Use await inside a for...of loop when each operation should finish before starting the next. forEach() does not wait for an async callback.
const results = [];
for (const value of [1, 2, 3]) {
const result = await Promise.resolve(value * 2);
results.push(result);
}
console.log(results.join(", "));Output
2, 4, 6
Collect independent work
map() can produce an array of promises, then Promise.all() waits for all of them. Limit concurrency for large real workloads instead of starting unbounded work.
const results = await Promise.all([2, 4].map(async value => value + 1));
console.log(results.join(", "));Output
3, 5
Put it into practice
- Predict each result before running the example.
- Complete the coding task, then explain why your solution works.
Try it yourself
Code runs on this device. When you are signed in, drafts sync to your account.
Wait for every calculation
Wait for the array of promises before summing the returned values. Display total.
Await Promise.all(), then reduce the resulting numbers.