等待后映射功能下的循环序列中断



我是异步等待承诺方法的新手。学习 async & await 的基本部分。我处于想要按顺序执行任务的情况,现在为此我编写了代码,但循环会中断序列。

我的代码是这样的:

const myAsyncFunction = async () => {
try {
let db1Data = await MyCollection1Name.find().exec();
if (db1Data.length > 0) {
//Suppose this collection have sector element which is array and have 5 values
let newData = db1Data[0].sector;
await Promise.all(
newData.map(async(x, i) => {
let db2Data = await MyCollection2Name.find().exec();
console.log(i)// Here My loop is break. It not print the value in sequential order. Although this will call after await
})
)
}
} catch (e) {
console.log(e)
}
}
myAsyncFunction()

谁能指导我哪里做错了??

任何帮助或建议真的非常感谢。

映射中的函数是异步的,因此返回一个 promise。它们将按顺序开始执行,但可能不会以相同的顺序完成。不过,Promise.all 上的等待将以正确的顺序返回映射的数组。

如果你想按顺序做它们,那么像这样使用reduce:

newData.reduce(
async (acc, curr) => acc.then(res => MyCollection2Name.find().exec()),
Promise.resolve()
)

最新更新