为什么async.each nodejs无法正常工作?

时间:2016-05-21 12:33:53

标签: javascript mysql node.js

我尝试使用async.each函数从两个查询中获取包含结果的数组。之后,我需要在网页中呈现此结果。

async.each函数可以正确计算变量结果,但是,我无法将此变量导出到函数外部并进行渲染,我不明白为什么。

这里我附上了代码,我测试了它。我意识到,当我打电话给#34; callback1"函数(错误)不起作用,我没有在控制台中获取变量列表(所以我以后不能再渲染它)。如果有人可以帮助我,我将不胜感激。非常感谢。

    var list = [];

    async.each(data, 
    function(elem, callback1){
        var classgene = '';
        var custom_gene = {};
        custom_gene = {Name_Gene: elem['Name_Gene']};

        if (elem['Type_Gene'] == "reference") {
            async.waterfall([
            function(callback2){
                var id = elem['Id_Genes'];
                geneModel.getGenesRefClass(id, function(error, data2){
                    classgene = data2[0]['Class_Name'];
                    custom_gene['classgene'] = classgene;
                    callback2(custom_gene);
                });
            },
            ], function(custom_gene, err){
                list.push(custom_gene);
                console.log(list);
                callback1();
            });
        }
    }, function(err){
        // if any of the saves produced an error, err would equal that error
        if(err){
            console.log(list);
        }else{
            console.log(list);
        }
    });

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 它没有正确调用callback2()。它应该是callback2(null, custom_gene)(第一个参数是为错误保留的,或null如果没有任何错误)。您最好还应检查error;
  • 返回的geneModel.getGenesRefClass()
  • 上一期也意味着您需要交换function(custom_gene, err)的参数(它应该成为function(err, custom_gene));
  • elem['Type_Gene']不等于"引用" 时,您仍应致电callback1(),否则async.each()不知道代码已完成;

所以代码会变成这样:

var list = [];

async.each(data, function(elem, callback1) {
  var classgene   = '';
  var custom_gene = { Name_Gene : elem['Name_Gene'] };

  if (elem['Type_Gene'] == "reference") {
    async.waterfall([
      function(callback2) {
        var id = elem['Id_Genes'];
        geneModel.getGenesRefClass(id, function(error, data2){
          if (error) return callback2(error);
          classgene = data2[0]['Class_Name'];
          custom_gene['classgene'] = classgene;
          callback2(null, custom_gene);
        });
      },
    ], function(err, custom_gene) {
      // If you want to propagate errors, uncomment the following:
      // if (err) return callback1(err);
      list.push(custom_gene);
      console.log(list);
      callback1();
    });
  } else {
    callback1();
  }
}, function(err){
  // if any of the saves produced an error, err would equal that error
  if (err) {
    console.log('An error occurred!', err);
  }
  console.log(list);
});