async map Returns An Array Of Promises
map with an async callback collects promises, not values: Promise.all awaits the already-concurrent requests, while await inside for..of runs sequentially.
Code
// Array.prototype.map returns synchronously: with an async callback you collect Promises,
// not values - you must await them all before you actually have the data
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const fetchProfile = async (id) => {
await sleep(20);
return { id, plan: id.startsWith('a') ? 'pro' : 'free' };
};
async function main() {
const ids = ['a1', 'b2', 'c3'];
const mapped = ids.map((id) => fetchProfile(id));
console.log('map collects promises:', mapped.every((v) => v instanceof Promise));
console.log('mapped[i].plan is undefined:', mapped[0].plan === undefined);
// Promise.all waits for all three: the requests already fired concurrently during map
const profiles = await Promise.all(mapped);
console.log('awaited:', profiles.map((p) => `${p.id}:${p.plan}`).join(' | '));
// Sequential alternative: await one by one in for...of - each starts only after the previous finishes
const sequential = [];
for (const id of ids) sequential.push(await fetchProfile(id));
console.log('sequential count:', sequential.length);
}
main();Output
Captured from a sandboxed run of this snippet in the build pipeline.
map collects promises: true
mapped[i].plan is undefined: true
awaited: a1:pro | b2:free | c3:free
sequential count: 3How the snippet works
async map Returns An Array Of Promises keeps everything in the functions sleep, fetchProfile and main.
One loop does the cycling here: for (const id of ids) sequential.push(await fetchProfile(id));. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
The result comes back as an object carrying id.
Applying it
The primary signature is const sleep = (ms)
The run emits 4 labeled sections — map collects promises:, mapped[i].plan is undefined:, awaited:, sequential count: — one per step.
main sequences fetchProfile; executing the file runs that flow once.
The call returns id.
Statements that matter
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const profiles = await Promise.all(mapped);
for (const id of ids) sequential.push(await fetchProfile(id));
FAQ
- Does `sleep` modify its input?
- The input survives unchanged; what you get back is a newly constructed value.
- What does async map Returns An Array Of Promises print when run?
- Run it as a complete program — the output lines carry labels such as `map collects promises:`, `mapped[i].plan is undefined:`, `awaited:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.