Using async-await with arr.map()
Satej Bidvai
Posted on January 12, 2023
While working on a task today, I had to populate my array of objects using my database.
Instinctively, I used the map
function. The code looked something like this:
const dataList = [
{ type: "test__1" },
{ type: "test__2" },
{ type: "test__3" },
{ type: "test__4" }
];
const modifiedList = dataList.map(async (item) => {
// Get additional properties from DB
const dataFromDB = await DataModel.findOne({
type: item.type
});
return { ...item, dataFromDB };
});
βοΈ Did you spot the error?
ππ½ In dataList.map()
, we are returning an array of promises and not an array.
ππ½ Hence, the modifiedList
will look something like this:
β‘οΈ The Solution?
Simple! We just need to wrap our function with await Promise.all
so that our array of promises is resolved to the desired modifiedList
.
const modifiedList = await Promise.all(
dataList.map(async (item) => {
// Get additional properties from DB
const dataFromDB = await DataModel.findOne({
type: item.type
});
return { ...item, dataFromDB };
});
);
π πͺ π
π©
Satej Bidvai
Posted on January 12, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
javascript npm vs yarn vs pnpm: A Comprehensive Guide to Choosing the Right Package Manager
August 12, 2024