【问题标题】:How to run async code inside each() function?如何在 each() 函数中运行异步代码?
【发布时间】:2019-12-19 02:16:08
【问题描述】:

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

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

【问题讨论】:

    标签: node.js cheerio


    【解决方案1】:

    尝试使用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
        }
    );
    

    【讨论】:

    • 为什么是whilst 而不是eachSeries
    【解决方案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);
    

    希望这会有所帮助。

    【讨论】:

    • 我建议使用i+1 而不是++i。后者意味着您依赖于预增量的副作用,这是不正确的。
    猜你喜欢
    • 2020-12-31
    • 1970-01-01
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 2021-08-17
    • 2022-11-16
    • 2015-07-19
    • 1970-01-01
    相关资源
    最近更新 更多