简体   繁体   English

在foreach中请求api

[英]request api in foreach

I have an array of data, against which I query an api using request . 我有一个数据array ,我可以使用request查询一个api With a callback executing after each response for the request that is made. 在对请求作出的每个响应之后执行callback However, in doing so, I end up launching parallel requests for all the items in the array. 但是,这样做最终导致对数组中的所有项目发起并行请求。 Here is what I am doing: 这是我在做什么:

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

I want to setTimeOut of x seconds in the above code. 我想在上面的代码中设置x seconds setTimeOut Should I implement a naive delay after each request? 我应该在每次请求后实施天真的延迟吗? Or something else? 或者是其他东西?

Updated : parallel request to series of request. 已更新:将并行请求更改为一系列请求。

You should use series of request. 您应该使用一系列请求。 use async module. 使用async模块。 see below 见下文

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 loop will ideally end in no time, so you can first add all query parameters in queryPool and then execute them one by one. 理想情况下,forEach循环将立即结束,因此您可以首先在queryPool中添加所有查询参数,然后一个一个地执行它们。

You can refer to this code. 您可以参考此代码。

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

This code assumes function given in request executes in all conditions, failure or success. 该代码假定请求中给定的功能在所有条件下(失败或成功)均执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在 foreach 中发送多个 POST API 请求的最佳实践 - Best practice to send multiple POST API request in foreach 反应 - 在每个 forEach API 请求完成后设置 State - React - Set State after every forEach API Request has completed api中的foreach obj如何发出另一个请求 - how foreach obj from api make another request 无法从 API 使用 foreach 循环和 Fetch API 获取多个数据获取请求 - Can't get multiple data from API using foreach loop with Fetch API get request 我正在尝试根据使用 forEach 的另一个 API 请求的结果发出 API 请求。 我如何在不使用 forEach 的情况下存档相同的结果 - I am trying to make an API request based on the result of another API request using forEach. How I could archive the same result without using forEach node / express.js-带有API请求的forEach循环将结果推送到数组,但数组保持为空 - node/express.js - forEach loop with request to API pushes result to array, but array remains empty Javascript - forEach 不是 function API - Javascript - forEach is not a function API 对 forEach 内部的 firebase 的异步请求 - Async request to firebase inside forEach forEach 内部的 Http 请求 - NodeJS - Http Request inside forEach - NodeJS forEach 不是 function omdb 和 api 快递 - forEach is not a function omdb and api express
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM