【问题标题】:Async.whilst with requests and unknown page limit - how to make requests asynchronous?带有请求和未知页面限制的 Async.whist - 如何使请求异步?
【发布时间】:2015-03-31 13:21:04
【问题描述】:

所以我写了一个运行良好的脚本,但我想让请求异步。目前,每一个都在前一个完成后运行,我不得不这样做,因为我无法知道总页数。我必须点击请求,直到出现错误。

有没有更好的方法来编写这段代码?

var getResponse = 'true'; var newNum = 0; var 响应 = [];

async.while( 功能 () { // 启动异步while循环 返回 getResponse == 'true';

},
function (callback) {
    // calls everytime
    newNum++;
    console.log('num',newNum);

    var options = {
        url: 'http://upload-api.kooaba.com/api/v4/buckets/sdfsfsfsfsdfsd/items?page='+newNum,
    }

    request(options, function(error, response, body) {

      var info = JSON.parse(body);

      if(info.offset) {
        getResponse = false;
        console.log('end of the records');
        console.log("All loaded.");
        var jsonSize = _.size(responses);
        console.log('size',jsonSize);
        res.json(responses);

      }
      else {
        _.each(info, function(obj) {
          var imageObj = {
            uuid : obj.uuid,
            enabled: obj.enabled,
            title: obj.title,
            itemCode: obj.reference_id,
            num_images: obj.num_images,
            bucket: 'uk'
          }
          responses.push(imageObj);
      });
        callback();
      }


      });

},
function (err) {
    // End loop
    console.log('end');
}

);

【问题讨论】:

    标签: node.js asynchronous request underscore.js


    【解决方案1】:

    Async.js 倾向于处理已知的数据集,一旦启动就不会接受对它们的更改。

    由于没有其他人回复,我正在为基于循环的应用程序处理提出一个总体思路。这是一种使用 同步 while 循环来完成您所寻求的事情的 hacky 方式,尽管这可能需要优化,因为它可能证明 CPU 成本很高:

    var flag = false; // Will be used to indicate loop break time.
    var expectedResponses = 0; // Will count sent requests
    var arrRequests = []; // Will be used as the queue, constantly getting requests pushed.
    var arrResponses = []; // Will be used to keep the responses.
    
    while (!flag || expectedResponses < arrResponses.length) {
        if (arrRequests.length) {
            var requestParams = arrRequests.pop();
            expectedResponses++;
            request(requestParams, function cb(err, res) {
                if (err) {
                    // Handle error and:
                    expectedResponses--;
                    return;
                }
                arrResponses.push(res);
            });
        }
    }
    
    // Process responses here.
    // This code will not be reached before flag is raised, AND queue is processed.
    

    说明:此同步循环不等待回调。每次处理内部代码时都会进行迭代,并达到关闭}。原因是它在等待返回声明,该声明以return null; 形式接收

    应手动引发注意标志,以便在所有请求都收到响应后中断循环。 此外,您可能需要考虑将其重写为基于事件,具有新的请求事件,以及在引发标志并收到最后一个响应时触发的第二个事件..

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-25
      • 1970-01-01
      • 1970-01-01
      • 2013-10-23
      • 2014-08-22
      • 2017-12-11
      • 1970-01-01
      相关资源
      最近更新 更多