使用 async.js 和 node.js

Using async.js with node.js

Visit.js - 请注意,folloup.id 指的是 0 或 "n" 次访问(如树)

var visitSchema = new Schema({
  code : {type: String, trim: true, required: false, default: ""},
  Client : {
    id: {type: Schema.Types.ObjectId, ref: 'Client'},
  },
  attendant : [{
    name : {type: String, trim: true, required: false, default: ""},
  }],
  followup : [{ 
    id : {type: Schema.Types.ObjectId, ref: 'Visit'}
  }],
});

Client.js

var clientSchema = new Schema({
  name: {type: String, trim: true, required: false, default: ""}
});

所以,我尝试这样做,但它不起作用。为什么不呢?

Visit.find(function(err, visits) {
  var visitCards = new Array();
  async.eachSeries(visits, function(visit, callback) {
    var visitCard = new VisitCard();
    async.series([
      function(callback){
        Client.findById(visit.Client.id, function(err, client) {
          visitCard.client = client.name;
          callback();
        });
      },
      function(callback){
        visit.followup.forEach(function(followup){
          Client.findById(followup.Client.id, function(err, lfollowup) {
            var pfollowup = new visitCard.followup();  
            ...
            visitCard.followup.push(pFollowup);
            callback();
          });
        });
      }
    ],
    function(err, results){
      ...
      visitCards.push(visitCard);
    });
  },
  function(err){
    res.render('visits/index', { visitCards: visitCards});
  });
});

好像是:

客户端的回调 return 在 "async.eachSeries(visits, function(visit, callback)" 执行之后。

"visit.followup.forEach" 在 Client.findById 执行之前完成。

forEach 并行执行,因此 forEachClient.findById 之前完成。

因此您可以使用 eachSeries 而不是 forEach