Promise.all Resolves An Object Of Promises
Collect parallel work under named keys with Promise.all over Object.values, then pair settled results back with Object.keys so responses land on their labels.
Code
const loadPrice = (symbol) => Promise.resolve({ symbol, cents: symbol.length * 101 });
async function loadQuotes(symbols) {
// 并行任务先按 key 装进对象,全部发起
const jobs = Object.fromEntries(symbols.map((symbol) => [symbol, loadPrice(symbol)]));
const keys = Object.keys(jobs);
// Promise.all 一次性等待:结果顺序与 Object.values 一致
const settled = await Promise.all(Object.values(jobs));
// 按 key 配对回填,结果不会错位
return Object.fromEntries(keys.map((key, index) => [key, settled[index]]));
}
const quotes = await loadQuotes(["acme", "globex", "initech"]);
for (const [symbol, quote] of Object.entries(quotes)) {
console.log(`${symbol}: ${(quote.cents / 100).toFixed(2)}`);
}
Output
Captured from a sandboxed run of this snippet in the build pipeline.
acme: 4.04
globex: 6.06
initech: 7.07How the snippet works
Promise.all Resolves An Object Of Promises comes down to the functions loadPrice and loadQuotes.
A single loop drives the file — for (const [symbol, quote] of Object.entries(quotes)). Every asynchronous step is awaited, so rejections surface where the call happens.
Watch out for
- Runs on the standard library alone; nothing to install.
Putting it to use
Signature: const loadPrice = (symbol)
Core lines
const loadPrice = (symbol) => Promise.resolve({ symbol, cents: symbol.length * 101 });
return Object.fromEntries(keys.map((key, index) => [key, settled[index]]));
const settled = await Promise.all(Object.values(jobs));
FAQ
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `loadPrice`, `loadQuotes` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.