我正在使用 mongo,需要对循环内的每个项目进行异步调用。我想在循环内的所有 promise 完成后执行另一个命令,但到目前为止,循环中的 promise 似乎是在循环之后的 then 中的代码之后完成的。
基本上我希望顺序是
循环 promise 然后 其他代码
而不是现在的样子
其他代码 循环 promise
MongoClient.connect(connecturl)
.then((client) => {
databases.forEach((val) => {
val.collection.forEach((valcol) => {
client.db(val.databasename).stats() //(This is the async call)
.then((stats) => {
//Do stuff here with the stats of each collection
})
})
})
})
.then(() => {
//Do this stuff after everything is finished above this line
})
.catch((error) => {
}
对此的任何帮助将不胜感激。
最佳答案
假设您正在使用的东西 .forEach()
对于可迭代对象(数组或类似的东西),您可以使用 async/await
序列化 for/of
循环:
MongoClient.connect(connecturl).then(async (client) => {
for (let db of databases) {
for (let valcol of db.collection) {
let stats = await client.db(db.databasename).stats();
// Do stuff here with the stats of each collection
}
}
}).then(() => {
// Do this stuff after everything is finished above this line
}).catch((error) => {
// process error
})
如果您想坚持使用 .forEach()
循环,如果您并行执行操作并使用 Promise.all()
,则可以使其全部工作。知道一切何时完成:
MongoClient.connect(connecturl).then((client) => {
let promises = [];
databases.forEach((val) => {
val.collection.forEach((valcol) => {
let p = client.db(val.databasename).stats().then((stats) => {
// Do stuff here with the stats of each collection
});
promises.push(p);
});
});
return Promise.all(promises);
}).then(() => {
// Do this stuff after everything is finished above this line
}).catch((error) => {
// process error here
});
关于javascript - 如何在 Javascript 中的 forEach 循环内正确链接 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48603835/