我在串行调用生成的函数时遇到了问题。我使用的是异步库,当不需要深入的回调调用时,代码似乎可以正常工作。当我添加真实场景时,它会抛出错误。
下面是一个示例,返回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);
});
}现在添加真正的场景,比如下载站点,然后放入回调:
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;
}Error是这样的,即使传递的不是结果迭代器变量i:
/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)//编辑
只有添加到完整回调中的结果才是第一个,其他函数永远不会被调用。此外,对于信息,函数会返回对象文字,如果这很重要的话。
发布于 2012-04-22 16:27:28
您的代码没有任何问题。创建一个简单的测试用例显示了这一点。
我创建了一个模拟:
Scrape = function() {
this.pageSet = 5;
}
Scrape.prototype.setIndex = function() {
}
Scrape.prototype.getSite = function(cb) {
cb('works');
}并调用run方法,输出预期的:
[ 'works', 'works', 'works', 'works', 'works' ]所以问题出在别的地方。您是否尝试过检查run方法中的functionList变量?
发布于 2012-04-22 21:59:31
谢谢你@KARASZI István,上面的所有代码都是正确的,问题似乎在其他地方。最深的回调被调用了多次,但外部的回调只被调用了一次。
https://stackoverflow.com/questions/10266301
复制相似问题