在 foreach 中请求 API

request api in foreach

本文关键字:API 请求 foreach      更新时间:2023-09-26

我有一个数据array,我使用 request 查询api。在对发出的请求的每个响应之后执行callback。但是,在这样做的过程中,我最终会为数组中的所有项目发起并行请求。这是我正在做的事情:

exports.getData = function(arr, cb){
    arr.forEach(function(data){
        var query = {
            //some data here
        };
       request({
           url: 'http://x/y',
           json: query,
           method: 'POST',
           headers: {
               'Content-Type': 'application/json'
           }
       }, function(error, res, body){
           if (error){
               console.log(error);
           } else{
               cb(res.body);
           }
       });
    });
};

我想在上面的代码中setTimeOut x seconds。我应该在每个请求后实施天真的延迟吗?还是别的什么?

更新:并行请求到一系列请求。

你应该使用一系列请求。 使用async模块。见下文

exports.getData = function(arr, cb){
  // make an array of function
  var funcArray = [];
  arr.forEach(function(data){
      var query = {
          //some data here
      };
     funcArray.push(function(callback){    
        request({
           url: 'http://x/y',
           json: query,
           method: 'POST',
           headers: {
               'Content-Type': 'application/json'
           }
        }, function(error, res, body){
           // 5 second interval for each request
           setTimeout(function(){ callback(error, body); }, 5000);
        });
      });
  });

  // now run all tasks on series
  async.series(funcArray,function(err, result){
      // now you will get result for all request
      // handle error
      // do what ever you want with result
  });
}

forEach 循环理想情况下会立即结束,因此您可以先在 queryPool 中添加所有查询参数,然后逐个执行它们。

您可以参考此代码。

exports.getData = function(arr, cb){
    var queryPool = [];
    function execQuery(){
       if(queryPool.length == 0) return
       var query = queryPool.slice(0,1)
       queryPool = queryPool.slice(1,queryPool.length)
       request({
           url: 'http://x/y',
           json: query,
           method: 'POST',
           headers: {
               'Content-Type': 'application/json'
           }
       }, function(error, res, body){
           if (error){
               console.log(error);
           } else{
               cb(res.body);
           }
           execQuery();
       });
    }
    arr.forEach(function(data){
        var query = {
            //some data here
        };
       queryPool.push(query);
    });
    execQuery();
};

此代码假定请求中给出的函数在所有条件(失败或成功)中执行。