2012-09-09 53 views
0

我正在使用parallel function in Async.js,由于某种原因,最终回调没有执行,我也没有看到任何地方发生错误。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(函数)内部,我称之为回调函数,所以这就是黄金。

任何人都有任何想法,为什么这可能无法正确执行?

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

谢谢!

回答

3

分析什么是逐行发生,首先是这样的:

var genFileFunc = generateFileFunc(...); 

因为你的函数generateFileFunc返回功能,所以变量genFileFunc是下面的函数

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

现在很明显,这函数返回什么也没有(没有return声明)。而且明显通过没有什么我了解JavaScript的内置undefined常量。特别是你有

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

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

很难说如何解决这个问题,而不知道generateFile究竟是什么,但我会试试它。尝试简单地这样做:

callItems.push(genFileFunc); 

,因为你要推功能callItems的功能,这是undefined没有结果。

+0

你钉了它。出于某种原因,我一直告诉自己,我正在generateFileFunc调用中返回一个函数。但是,正如你所说的,在数组推送上,我正在执行方法而不是将函数作为参数传递。很好的解释。 –

2

好奇。

迄今为止的猜测:在generateFile里面,RETURN回调而不是调用它。

+0

乔什既定目标 - 你是对的。然而,直到我按照奇怪的逻辑发布,它才点击。尽管如此,仍然赞成你。谢谢! –

1

可以实现与

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