【问题标题】:Async.js Parallel Callback not executingAsync.js 并行回调未执行
【发布时间】:2013-02-11 23:02:08
【问题描述】:

我正在使用parallel function in Async.js,由于某种原因,最终的回调没有被执行,我没有看到任何地方发生错误。

我正在动态创建一个函数数组,这些函数被传递给并行调用:

// 'theFiles' is an array of files I'm working with in a code-generator style type of scenario
var callItems = [];
theFiles.forEach(function(currentFile) {

      var genFileFunc = generateFileFunc(destDir + "/" + currentFile, packageName, appName);

      callItems.push(genFileFunc(function(err, results) {
        if(err) {
          console.error("*** ERROR ***" + err);
        } else {
          console.log("Done: " + results);  
        }

      }));

    });

    async.parallel(callItems, function(err, results) {
      console.log(err);
      console.log(results);
      if(err) {
        console.error("**** ERROR ****");
      } else {
        console.log("***** ALL ITEMS HAVE BEEN CALLED WITHOUT ERROR ****");  
      }
    });

然后在一个外部函数中(在上面执行 forEach 的函数之外)我有 generateFileFunc() 函数。

// Function that returns a function that works with a file (modifies it/etc). 
function generateFileFunc(file, packageName, appName) {
  return function(callback) {
    generateFile(file, packageName, appName, callback);
  }
}

我查看了this SO post,它帮助我到达了我所在的位置。但是最终的回调没有被执行。并行调用中的所有项目都在执行。在最底部的 gnerateFile (function) 内部,我调用了回调,所以这是金色的。

有人知道为什么这可能无法正常执行吗?

最终结果是并行处理每个函数调用,然后在我完成时收到通知,以便我可以继续执行其他一些指令。

谢谢!

【问题讨论】:

    标签: node.js async.js node-async


    【解决方案1】:

    逐行分析正在发生的事情,从以下开始:

    var genFileFunc = generateFileFunc(...);
    

    由于你的函数generateFileFunc返回函数,所以变量genFileFunc是一个跟随函数

    genFileFunc === function(callback) {
        generateFile( ... );
    };
    

    现在很明显,这个函数返回 nothing(没有return 语句)。很明显,nothing 我理解 JavaScript 的内置 undefined 常量。特别是你有

    genFileFunc(function(err, results) { ... } ) === undefined
    

    这是调用它的结果。因此,您将undefined 推送到callItems。难怪它不起作用。

    如果不知道generateFile 究竟做了什么,很难说出如何解决这个问题,但无论如何我都会尝试。尝试简单地这样做:

    callItems.push(genFileFunc);
    

    因为你必须将函数推送到callItems,而不是函数的结果,即undefined

    【讨论】:

    • 你成功了。出于某种原因,我一直告诉自己,我在 generateFileFunc 调用中返回了一个函数。但是,正如您所说,在数组推送时,我正在执行该方法,而不是将该函数作为参数传递。很好的解释。
    【解决方案2】:

    好奇。

    迄今为止的最佳猜测:在 generateFile 内部,返回回调而不是调用它。

    【讨论】:

    • 乔希 - 你是对的。但是,直到我按照怪胎发布的逻辑,它才单击。不过还是给你点赞。谢谢!
    【解决方案3】:

    您可以通过以下方式实现既定目标

    async.map(theFiles, function(file, done) {
      generateFile(destDir + "/" + file, packageName, appName, done);
    }, function(err, res) {
      // do something with the error/results
    });
    

    【讨论】:

      猜你喜欢
      • 2013-06-12
      • 2014-03-11
      • 1970-01-01
      • 2019-08-23
      • 2018-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多