Start Promises Before Awaiting Them
Start independent tasks before awaiting them so durations overlap; completion order proves concurrency while the awaited array keeps start order.
Code
// 先启动所有独立任务,再统一 await:耗时重叠而不是相加
const order = [];
const task = (name, ms) =>
new Promise((resolve) =>
setTimeout(() => {
order.push(name);
resolve(name);
}, ms));
// 两个任务同时开始计时
const slow = task('slow-40ms', 40);
const quick = task('quick-10ms', 10);
// 反例:把启动写成 const slow = await task(...) 会变成串行
const results = await Promise.all([slow, quick]);
console.log('completion order:', order.join(' -> '));
console.log('results keep start order:', results.join(','));Output
Captured from a sandboxed run of this snippet in the build pipeline.
completion order: quick-10ms -> slow-40ms
results keep start order: slow-40ms,quick-10msInside the snippet
Count the function task as the entire surface area of Start Promises Before Awaiting Them.
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Using it
Entry signature: const task = (name, ms)
Look for the completion order:, results keep start order: prefixes when the file runs; they tie each line to its step.
Key statements
const results = await Promise.all([slow, quick]);
new Promise((resolve) =>
setTimeout(() => {
order.push(name);
resolve(name);
}, ms));
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. The file defines `task` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.