异步调用生成的函数串行

时间:2012-04-22 08:12:15

标签: javascript node.js asynchronous

我在串行调用生成的函数时遇到问题。我正在使用异步库,当没有需要深度回调调用时,代码似乎工作。当我添加真实场景时,它会抛出错误。

以下是有效的示例,返回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;
}

错误是这样的,即使传递而不是结果迭代器变量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)

//编辑

只有添加到完整回调中的结果才是第一个,其他函数永远不会被调用。 另外,对于信息,函数返回对象文字,如果这很重要。

2 个答案:

答案 0 :(得分:2)

您的代码没有任何问题。创建一个简单的测试用例就可以显示出来。

我创建了一个模拟:

Scrape = function() {
  this.pageSet = 5;
}

Scrape.prototype.setIndex = function() {
}

Scrape.prototype.getSite = function(cb) {
  cb('works');
}

并调用run方法输出预期的结果:

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

所以问题出在其他地方。您是否尝试检查functionList方法中的run变量?

答案 1 :(得分:0)

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