Async / Await with Array.prototype.map() – What’s the Trick?

I’ll try to make this as simple as possible.

If you want to map asyncroniously, the map() will return a list of promises so the new array will return a promise for each call. Makes sense right?
Here is the “oups” what’s happening code?

//1/3 of our fruits are rotten, display how many of each are rotten
const basket = [ { apples: 33 }, { pears: 21 }, { peaches: 12 } ]
const rotten = basket .map(async (obj) => { return obj.key/3; });

console.log(rotten);

In this case map() will look a list of promises. The actual values in rotten will appear when everything is resolved. That’s why a Promise.all() is necessary here, because it will return the values when all the promises are resolved.

The correct code would be:

//1/3 of our fruits are rotten, display how many of each are rotten
const basket = [ { apples: 33 }, { pears: 21 }, { peaches: 12 } ]
const rotten = basket .map(async (obj) => { return obj.key/3; });

console.log(rotten);
const result = Promise.all(rotten).then((result)=>console.log(result));

Leave a Reply