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: “t…


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Satej Bidvai

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:

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 };
    });
);


This content originally appeared on DEV Community 👩‍💻👨‍💻 and was authored by Satej Bidvai


Print Share Comment Cite Upload Translate Updates
APA

Satej Bidvai | Sciencx (2023-01-12T19:25:10+00:00) Using async-await with arr.map(). Retrieved from https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/

MLA
" » Using async-await with arr.map()." Satej Bidvai | Sciencx - Thursday January 12, 2023, https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/
HARVARD
Satej Bidvai | Sciencx Thursday January 12, 2023 » Using async-await with arr.map()., viewed ,<https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/>
VANCOUVER
Satej Bidvai | Sciencx - » Using async-await with arr.map(). [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/
CHICAGO
" » Using async-await with arr.map()." Satej Bidvai | Sciencx - Accessed . https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/
IEEE
" » Using async-await with arr.map()." Satej Bidvai | Sciencx [Online]. Available: https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/. [Accessed: ]
rf:citation
» Using async-await with arr.map() | Satej Bidvai | Sciencx | https://www.scien.cx/2023/01/12/using-async-await-with-arr-map/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.