在迭代到下一个循环之前,如何等待内部完成?

时间:2018-07-27 10:40:22

标签: javascript node.js express asynchronous

嗨,我想为每个实现嵌套。但是在嵌套的for循环完成其执行之前,for循环不应迭代到下一个。我已经尝试过使用asyn.forEachOf,但是首先执行了for循环,而没有等待第二次for循环。我已经实现了

async.forEachOf(playerIds, function (playerId, key, playerCallback) {
    console.log(playerId);
    //Find coach rating for every player's goals
    DateInfo.find({
        coachId: userId,
        playerId: playerId,
        coachRemoved: false
    }).select('objectiveId frequencyId').populate({
        path: 'objectiveId', match: {'deleted': {$ne: 2}}, select: {'name': 1}
    }).exec(function (error, coachDateInfos) {
        if (error) {
            response.status(200).json({message: error});
        } else {
            console.log(coachDateInfos);
            playerCallback()
        }
    })
});

我还没有发布异步功能。我有两个玩家ID,它先打印两个玩家ID,然后再打印coachDateInfos。

2 个答案:

答案 0 :(得分:1)

这是因为for-loop同步操作,而Model.find().exec()异步操作。您不能将两者混在一起。您可以执行以下操作(没有async lib):

app.get(async (req, res) => {
  const promises = []

  playerIs.forEach(playerId => {
    const promise = DateInfo
      .find({coachId: userId, playerId, coachRemoved: false})
      .select('objectiveId frequencyId')
      .populate({path: 'objectiveId', match: {'deleted': {$ne: 2}}, select: {'name': 1})
      .exec()

      promises.push(promise)
  })

  try {
    res.json(await Promise.all(promises))
  } catch (err) {
    res.status(200).json(err);
  }
})

答案 1 :(得分:0)

var arrayOfFuncs = [];
for (var key in playerIds) {
    let player = playerIds[key];
    let func_1 = function(playerId,cb)
    {
        console.log(playerId);
        //Find coach rating for every player's goals
        DateInfo.find({
            coachId: userId,
            playerId: playerId,
            coachRemoved: false
        }).select('objectiveId frequencyId').populate({
            path: 'objectiveId', match: {'deleted': {$ne: 2}}, select: {'name': 1}
        }).exec(function (error, coachDateInfos) {
            if (error) {
                //response.status(200).json({message: error});
                cb(error, null);
            } else {
                console.log(coachDateInfos);
                cb(null, coachDateInfos);
            }
        })
    }
    arrayOfFuncs.push(func_1.bind(null,player));
}

async.parallel(arrayOfFuncs, function(errString, allResults) {
    if(errString) {
        console.log(errString);
    } else {
        console.log(allResults);
    }
})