Using array.map
with async/await
25 May 2021 in TIL
When using array.map
with an async
function you'll receive an array of pending promises back
js
let items = [1, 2, 3];items = items.map(async (v) => {await asyncMultiplyByTwo(v);});// [ Promise { <pending> }, Promise { <pending> }, Promise { <pending> } ]
Wrapping this in await Promise.all
allows you to use async
functions with array.map
whilst still receiving the raw data at the end
js
let items = [1, 2, 3];items = await Promise.all(items.map(async (v) => {await asyncMultiplyByTwo(v);}));// [ 2, 4, 6 ]