"Confused about handling async/await inside Array.map() in Node.js" #173366
-
Select Topic AreaQuestion BodyHi everyone , const fetchData = async (id) => { const process = async () => { console.log("Results:", results); process(); Instead of logging the fetched data, I just get an array of Promises: Results: [ Promise { }, Promise { }, Promise { } ] const results = await Promise.all(ids.map(fetchData)); But my doubt is: |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
|
if I'm getting it correctly, when you do: const results = ids.map(async (id) => {
const data = await fetchData(id);
return data;
});
this is why you saw: how to get Resolved ValuesYou need to wait for all the Promises to resolve. The standard way: const results = await Promise.all(ids.map(async (id) => {
const data = await fetchData(id);
return data;
}));
console.log(results);
// ["Data for 1", "Data for 2", "Data for 3"]Or, since const results = await Promise.all(ids.map(fetchData));Both are equivalent. why
|
| Approach | Returns | Execution |
|---|---|---|
map(async …) |
Array of Promises | Starts all async tasks immediately, concurrent |
await Promise.all(map(async …)) |
Array of resolved values | Waits for all tasks to finish, concurrent |
for…of + await |
Array of resolved values | Waits sequentially, one by one |
so,
map()doesn’t await async callbacks automatically- using
map(async …)is fine if you wrap it inPromise.allor otherwise handle the Promises - for sequential execution, use
for…of
Beta Was this translation helpful? Give feedback.
-
|
Usually await works inside the async function only, it does not care about the outer scope. Outside, the function scope it still returns a promise so map just gives you an array of promises . |
Beta Was this translation helpful? Give feedback.
-
|
Yes — this behaviour is expected.
That’s why your log shows: [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ] 🔑 Key Points:
const results = await Promise.all(ids.map(async (id) => {
const data = await fetchData(id); return data; }));
console.log(results); // ["Data for 1", "Data for 2", "Data for 3"]
📌 Final Takeaway: |
Beta Was this translation helpful? Give feedback.
-
|
Thanks to the whole team @jfullstackdev @PadhikariDev @itzdheerajsingh for the help! |
Beta Was this translation helpful? Give feedback.
Yes — this behaviour is expected.
Array.map()does not “await” anything. It just runs the callback for each element and returns a new array immediately.map(async …)is an array of Promises, not the resolved values.That’s why your log shows:
🔑 Key Points:
asyncfunction always returns a Promise. Even if youreturn "hello"; in an async function, it’s really returningPromise.resolve("hello")map()doesn’t know aboutasync . map()is synchronous — it doesn’t wait for Promises.Promise.all()If you want the final values, you need…