1

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

这是有效的示例,返回 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)

// 编辑

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

4

2 回答 2

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

于 2012-04-22T08:27:28.360 回答
0

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

于 2012-04-22T13:59:30.577 回答