繁体   English   中英

async.each中的异步函数未触发

[英]Asynchronous function inside async.each is not getting fired

谁能解释下面控制台日志的打印顺序? 我正在使用异步版本1.4.23。
响应包含两个项目。
输出:标签1
标签2
标签2
标签4
标签3
标签3

async.parallel([
  function(callback){
    detailsData.list({}, function(err, response) {
      if (!err) {
        console.log("label 1");
        async.each(response, function(item, cb) {
          console.log("label 2");
          itemList.getData(item, function(err, response) {
            console.log("label 3");
            }
            cb(err);
          });
        });
      }
      callback(err);
    });  
  },
  function (callback) {
    somefunction();
  }], function (err) {
    console.log("label 4");
  }  

为什么在标签4之前没有打印标签3?

您必须将从async.parallel获得的callback传递给async.each而不是立即调用它,否则并行执行将不会等待每个callback

async.parallel([
  function(callback){
    detailsData.list({}, function(err, response) {
      if (err) return callback(err); // <- still call it when you're not going for the each
      console.log("label 1");
      async.each(response, function(item, cb) {
        console.log("label 2");
        itemList.getData(item, function(err, response) {
          console.log("label 3");
          cb(err, response);
        });
      }, callback);
//       ^^^^^^^^
    });
  },
  function(callback) {
    somefunction();
    callback();
  }
], function(err) {
  console.log("label 4");
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM