在foreach循环中异步

时间:2018-05-08 16:38:38

标签: javascript asynchronous web

我需要在foreach中的每个异步方法结束时返回值。

我该怎么做?

 return backupModel.find({}).exec().then(backups => {
        backupBuild = []
        backups.forEach((backup, i) => {
            userDB.getC(backup.id).then((user) =>{
                backupBuild[i].client=user
            })
        })
        return backupBuild,
    });

2 个答案:

答案 0 :(得分:3)

尝试Promise.all

return backupModel.find({}).exec().then(backups =>
    Promise.all(backups.map(backup => userDB.getC(backup.id)))
).then(backupBuild => console.log(backupBuild));

答案 1 :(得分:0)

我也试过了:但是"无法设置属性'客户端'未定义"

return backupModel.find({}).exec().then(backups => {
    let backupBuild = [];
    let promises = [];
    backups.forEach((backup, i) => {
        promises.push(userDB.getCustomer(backup.idClient).then((user) =>{
            backupBuild[i]= backup;
            backupBuild[i].client= user;
        }))
    })
    Promise.all(promises).then(() => {return console.log(backupBuild)})
});