等待循环中的函数完成

Wait for functions in for loop to finish

本文关键字:函数 循环 等待      更新时间:2023-09-26

我在NodeJS中有一个for循环。循环内部是一个从数据库获取数据的函数。

var player2.schedule = {
  opponent: //string
  datetime: //date object
}
var schedule = "";
for (i=0; i<player2.schedule.length; i++) { 
  User.findOne({ id: player2.schedule[i].opponent }.select("name").exec(function(err, opponent) {
    schedule += opponent.name;
  });
}

每次循环时,循环都会将数据库调用的结果添加到变量schedule中。

现在我的问题是,如果在for循环之后有依赖于这个schedule变量的代码,它就不能。因为变量是在数据库调用的回调函数中更新的,所以for循环之后的任何代码都是异步发生的,所以变量没有及时更新。

如何确保下一批代码首先等待for循环和回调完成?

下面是一个使用async:的简单示例

var async = require('async');
async.each(player2.schedule, function(item, cb) {
  User.findOne({ id: item.opponent })
      .select("name")
      .exec(function(err, opponent) {
    if (err)
      return cb(err);
    schedule += opponent.name;
    cb();
  });
}, function(err) {
  if (err)
    throw err;
  console.log('All done');
});

您可以使用异步库函数whils()来等待所有查询完成:

var async = require('async');
var i = 0;
var len = player2.schedule.length;
async.whilst(
  function () { return i < len; },
  function (callback) {
    User.findOne({ id:player2.schedule[i].opponent}.select("name").exec(function(err, opponent) {
      schedule += opponent.name;
      i++;
      callback(null);   // assume no error (null)
    });
  },
  function (err) {
    // this function is executed after all queries are done
    // schedule now has everything from the loop
  } 
);