我有一些数据,希望每个人都能获得一些信息。
我想在过程开始时记录控制台,并在过程完成时记录数据,但是结果为我提供了与初始化时相同的数据。
我已经尝试使用异步/等待,但是它没有按预期工作。
这是我的代码
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);
结果还是一样。
[
{
name: 'User 1',
detail: 0
},
{
name: 'User 2',
detail: 0
},
{
name: 'User 3',
detail: 0
}
]
我的期望
[
{
name: 'User 1',
detail: "Detail Test"
},
{
name: 'User 2',
detail: "Detail Test"
},
{
name: 'User 3',
detail: "Detail Test"
}
]
您的代码存在3个问题:
getDetail
应该返回一个承诺,await
让其实际等待。const getDetail = () => new Promise((resolve) => {
setTimeout(() => {
resolve("Detail Test");
}, 3000);
}
Array.map
不会修改原始数组,强烈建议这样做,但是为了回答您的问题: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();
这是一支工作笔
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句