Reputation: 117
I have some array of data and would like each of them to get some information.
I would like to log the console when the process starts and log the data when it finished, but the result gives me the same data as when initialized.
I have tried using async / await but it does not work as I expected.
Here is my Code
const data = [
{
name: 'User 1',
detail: 0
},
{
name: 'User 2',
detail: 0
},
{
name: 'User 3',
detail: 0
}
];
function getDetail() {
setTimeout(() => {
return "Detail Test";
}, 3000);
}
async function mapping() {
await Promise.all(data.map(async (item) => {
item.detail = await getDetail();
}))
}
console.log("Start");
mapping();
console.log(data);
the result is still the same.
[
{
name: 'User 1',
detail: 0
},
{
name: 'User 2',
detail: 0
},
{
name: 'User 3',
detail: 0
}
]
My expectation
[
{
name: 'User 1',
detail: "Detail Test"
},
{
name: 'User 2',
detail: "Detail Test"
},
{
name: 'User 3',
detail: "Detail Test"
}
]
Upvotes: 1
Views: 69
Reputation: 6481
There are 3 problems with your code:
getDetail
should return a promise for await
to actually wait.const getDetail = () => new Promise((resolve) => {
setTimeout(() => {
resolve("Detail Test");
}, 3000);
}
Array.map
does not modify the original array, which is highly recommended but for the sake of answering your question:async function mapping() {
await Promise.all(data.map(async (item, i) => {
data[i].detail = await getDetail();
}))
}
async function run() {
console.log("Start");
await mapping();
console.log(data);
};
run();
Here's a working pen
Upvotes: 3