我正在与 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它帮助我到达了现在的位置。然而最终的回调并没有被执行。不过,并行调用中的所有项目都正在执行。在最底部的 ggenerateFile (函数)内部,我调用回调,所以这是黄金。
有人知道为什么这可能无法正确执行吗?
最终结果是并行处理每个函数调用,然后在完成后收到通知,以便我可以继续执行其他一些指令。
谢谢!
最佳答案
逐行分析正在发生的事情,从这里开始:
var genFileFunc = generateFileFunc(...);
由于您的函数 generateFileFunc
返回函数,因此变量 genFileFunc
是以下函数
genFileFunc === function(callback) {
generateFile( ... );
};
现在很明显,这个函数没有返回(没有return
语句)。显然,我什么都不懂 JavaScript 的内置 undefined
常量。特别是你有
genFileFunc(function(err, results) { ... } ) === undefined
这是调用它的结果。因此,您将 undefined
推送到 callItems
。难怪它不起作用。
在不知道 generateFile
到底做什么的情况下很难判断如何解决这个问题,但无论如何我都会尝试一下。尝试简单地这样做:
callItems.push(genFileFunc);
因为您必须将函数推送到callItems
,而不是函数的结果,这是未定义的
。
关于node.js - Async.js 并行回调未执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12341883/