javascript - 有没有办法在继续之前等待承诺?
问题描述
我有一些数据数组,并希望他们每个人都能获得一些信息。
我想在进程启动时记录控制台并在完成时记录数据,但结果给我的数据与初始化时相同。
我尝试过使用 async / await 但它没有按我的预期工作。
这是我的代码
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();
这是一支工作笔
推荐阅读
- python - 缓存结果似乎比重新计算结果慢
- r - 如何根据某些变量绘制条形图的条件彩色轮廓?
- java - 将 MySQL 数据库打包到 java se 应用程序
- r - 如何在 R 中使用 mapview() 标题给出地图?
- clang - 如何在 llvm ir 中创建 thread_local 变量?
- python - python函数应该总是返回一些值有什么原因吗?
- javascript - 如何从返回承诺的回调函数中获取数据?
- python - 将 GeoJSON 加载到 GeoPandas 数据帧中 - 格式错误或给出“引发 TypeError”
- python - 在等待数据库查询响应时从外部停止线程
- ruby-on-rails - 如何创建带有测试消息的新 ActiveModel::Error?