asynchronous调用串联生成的函数

我在串行调用生成的函数有问题。 我正在使用asynchronous库和代码似乎工作时没有深呼叫需要callback。 当我添加真实场景时,会引发错误。

这里是工作的例子,返回0到4的数组:

Scrape.prototype.generatePageFunctions = function() { var functionList = new Array(), self = this; for (var i = 0; i < this.pageSet; i++) { (function(i) { functionList.push(function(cb) { // Inner functions which will be called in seriers var timeoutTime = parseInt(Math.random() * 5000 + 3000, 10); setTimeout(function() { self.setIndex(i); //self.getSite(function) cb(null, i); }, timeoutTime); }); })(i); } return functionList; } Scrape.prototype.run = function() { var functionList = this.generatePageFunctions(); async.series(functionList, function(err, results) { console.log('Job is completed '); console.log(results); }); } 

现在添加真实的场景,如下载网站,然后把callback:

 Scrape.prototype.generatePageFunctions = function() { var functionList = new Array(), self = this; for (var i = 0; i < this.pageSet; i++) { (function(i) { functionList.push(function(cb) { // Inner functions which will be called in seriers var timeoutTime = parseInt(Math.random() * 5000 + 3000, 10); setTimeout(function() { self.setIndex(i); self.getSite(function(result) { // Async callback to pass the data cb(null, result); }); }, timeoutTime); }); })(i); } return functionList; } 

错误是这样的,即使通过而不是结果迭代器variables我:

 /home/risto/scrape/node_modules/async/lib/async.js:185 iterator(x.value, function (err, v) { ^ TypeError: Cannot read property 'value' of undefined at /home/risto/scrape/node_modules/async/lib/async.js:185:23 at /home/risto/scrape/node_modules/async/lib/async.js:108:13 at /home/risto/scrape/node_modules/async/lib/async.js:119:25 at /home/risto/scrape/node_modules/async/lib/async.js:187:17 at /home/risto/scrape/node_modules/async/lib/async.js:491:34 at /home/risto/scrape/scraper/scrape.js:114:13 at /home/risto/scrape/scraper/scrape.js:64:16 at Object.<anonymous> (/home/risto/scrape/scraper/engines/google.js:58:12) at Function.each (/home/risto/scrape/node_modules/cheerio/lib/api/utils.js:133:19) at [object Object].each (/home/risto/scrape/node_modules/cheerio/lib/api/traversing.js:69:12) 

//编辑

只有结果被添加到完整的callback是第一个,其他function从来没有被调用。 同样的信息函数返回对象文字,如果这很重要。

你的代码没有问题。 创build一个简单的testing用例表明。

我创造了一个模拟:

 Scrape = function() { this.pageSet = 5; } Scrape.prototype.setIndex = function() { } Scrape.prototype.getSite = function(cb) { cb('works'); } 

并调用run方法它输出预期:

 [ 'works', 'works', 'works', 'works', 'works' ] 

所以问题在别的地方。 你有没有试图检查你的run方法中的functionListvariables?

谢谢@KARASZIIstván,上面所有的代码都是正确的,这个问题似乎在别的地方。 最深的callback被多次调用,而外部的callback只调用一次。