DEV Community

Satej Bidvai
Satej Bidvai

Posted on

 

Using async-await with arr.map()

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 };
});
Enter fullscreen mode Exit fullscreen mode

❗️ 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:

console.log(modifiedList)

⚑️ 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 };
    });
);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

An Animated Guide to Node.js Event Loop

Node.js doesn’t stop from running other operations because of Libuv, a C++ library responsible for the event loop and asynchronously handling tasks such as network requests, DNS resolution, file system operations, data encryption, etc.

What happens under the hood when Node.js works on tasks such as database queries? We will explore it by following this piece of code step by step.