【发布时间】:2020-12-24 12:15:08
【问题描述】:
我有一个异步映射函数,但希望它同步执行,因为我需要在同一个循环中使用第一条语句的输出。但是即使使用 await 语句,地图也会异步运行,请您帮助理解为什么会发生这种情况。
我的用例是如果不存在则将记录插入 mongodb 并在循环中存在时更新它。 数据存在于数据库中,但在循环内查找失败,但在外部工作。
我的代码:
const doSomethingAsync = () => {
return new Promise(resolve => {
setTimeout(() => {
resolve(Date.now());
}, 1000);
});
};
await Promise.all(
modelVarients.map(async varient => {
console.log(`varient: ${varient._id}`);
console.log('1');
const onlineDevice = await Device.findOne({
model: varient._id,
});
console.log('2');
await doSomethingAsync();
console.log('3');
await doSomethingAsync();
console.log(JSON.stringify(onlineDevice));
await doSomethingAsync();
console.log('4');
return varient;
})
);
我得到的日志:
varient: 8 pro
1
varient: note
1
varient: iphone x
1
2
2
2
3
3
3
null
null
null
4
4
4
但我期望得到的:
varient: 8 pro
1
2
3
<actual response from db for 8 pro>
4
varient: note
1
2
3
<actual response from db for note>
4
varient: iphone x
1
2
3
<actual response from db for iphone x>
4
【问题讨论】:
-
使用 await modeVariants.reduce( async (...) => ) 而不是 map
-
@olkvin 谢谢,我会尝试在我的代码中实现
-
@EdwardRomero 感谢您向我指出一个类似的问题,是的,它帮助我了解了 reduce 以及如何链接承诺,下面来自 sashee 使用 async/await 的答案也非常有帮助
标签: javascript node.js asynchronous async-await async.js