2

我需要能够在每个循环内运行异步代码,并且在异步代码完成之前不进行迭代。

$("#items").children(".block-option-small").each(function(item) {
    request(newurl,function(err, resp, body) {  $ = cheerio.load(body);});
});
4

2 回答 2

2

尝试使用异步的 while 函数

var async = require("async"),
    request = require("request");

var items, count;

items = $("#items").children(".block-option-small");
count = 0;

async.whilst(
    function() {
        return count < items.length;
    },
    function(whilstCallback) {
        var item;

        item = items[count];
        count++;

        // build request url...

        request(newurl, function(err, resp, body) {
            $ = cheerio.load(body);

            // more processing...

            // process the next item
            whilstCallback();
        });
    },
    function(err) {
        // called when all items have been processed
    }
);
于 2014-06-15T16:59:34.370 回答
2

您不必为此使用该模块。你也可以这样写;

var items = $("#items").children(".block-option-small");
var count = items.length;

(function iterate(i) {
  if (i === count) {
    // iterations complete
    // do what you want to once iterations are complete
    process.exit(1);
  }

  var item = items[i];

  // async code
  request(newurl, function (err, resp, body) {
    $ = cheerio.load(body);
    iterate(i+1);
  });
})(0);

希望这可以帮助。

于 2014-06-15T17:13:50.947 回答