如何在each()函数中运行异步代码?

时间:2014-06-15 16:11:25

标签: node.js cheerio

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

     $("#items").children(".block-option-small").each(function(item){

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

2 个答案:

答案 0 :(得分:2)

尝试使用async's whilst function

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
    }
);

答案 1 :(得分: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);

希望这有帮助。