javascript - 如何在 Javascript 中的 forEach 循环内正确链接 Promise

标签 javascript mongodb promise

我正在使用 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/

相关文章:

javascript - 在 javascript 中创建一个 var;修改脚本以创建 var 用法?

javascript - 使用javascript获取div的偏移高度

node.js - 使用 $group stage 和 $sum 运算符聚合

javascript - 错误 : Cannot find module '../build/Release/bson' on Mac

javascript - 在 javascript 中将异步和同步工作与 async/await 和/或 Promise 混合在一起

javascript - 如何从 Node.js 快速操作处理程序执行延迟响应?

javascript - 动态创建链接

javascript - Angular 2 : setTimeout only called once

mongodb - mongodb insert 属性顺序重要吗?

Javascript 规范 : promises chains and omitted expectations