简体   繁体   English

多个Http请求被调用并存储在一个数组中,但是如何等待所有请求完成后再使用数组

[英]Multiple Http requests called and stored in one array, but how to wait until all requests finish before working with array

I have a array of values I want to loop over. 我有一个要遍历的值数组。 Each of these values will be used to make an http request to a server. 这些值中的每一个都将用于向服务器发出http请求。 From the server I will recieve a response for each request. 从服务器,我将收到每个请求的响应。 I want to store all these responses in a single array and then do work on the array once ALL requests have finished. 我想将所有这些响应存储在单个数组中,然后在所有请求完成后在数组上进行工作。 Due to the async nature of my code I am not sure how to make the application wait until all the requests have finished. 由于我代码的异步性质,我不确定如何使应用程序等待所有请求完成。 What is happening is I am making the requests, but the work I want to do with the array is already starting before ALL the requests have finished due to the async nature. 发生的事情是我在发出请求,但是由于异步的性质,我要对数组进行的工作已经在所有请求完成之前开始。 How can I make this code "synchronous" in the sence it waits until all requests have finished before starting to do the work with the listOfResponses array 我如何才能使此代码“同步”,使其等待所有请求完成之后才能开始使用listOfResponses数组进行工作

//import the require library to make http requests to a server
const request = require('request');

//values to be sent via a restful GET request 
const list = [
  'value_one',
  'value_two'
];

//store resoonses from GET request
var listOfResponses = [];

//loop through the list
list.forEach(function(word) {

  //Make a rest GET call to a server
  var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
  request(url, {
    json: true
  }, (err, res, body) => {
    if (err) {
      return console.log(err);
    }

    //store the response from the server into out array
    listOfResponses.push(body.response);
  });
});


/* ******************************* 
HERE I WANT TO DO STUFF WITH listOfResponses ONCE ALL THE REQUESTS FINISH
********************************** */

Just map it to an array of promises: 只需将其映射到一个promise数组即可:

  const promises = list.map(word => new Promise(resolve => {
   var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
   request(url, {
     json: true
   }, (err, res) => {
     if (err) {
       return reject(err);
     }   
     resolve(res.body);
   });
 }));

Then you can get all the results using Promise.all : 然后,您可以使用Promise.all获得所有结果:

 Promise.all(promises).then(results => {
  //...
 });

Simply check the responses each time a request ends: 每次请求结束时,只需检查响应即可:

//import the require library to make http requests to a server
const request = require('request');

//values to be sent via a restful GET request 
const list = [
  'value_one',
  'value_two'
];

//store resoonses from GET request
var listOfResponses = [];

//loop through the list
list.forEach(function(word) {

  //Make a rest GET call to a server
  var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + word;
  request(url, {
    json: true
  }, (err, res, body) => {
    if (err) {
      return console.log(err);
    }

    //store the response from the server into out array
    listOfResponses.push(body.response);
    check();
  });
});

// CHECK THE LIST
function check() {
  if (listOfResponses.length == list.length) {
    console.log("YAY! Here you have your responses", listOfResponses);
  }
}

This is an asynchronous scenario, a way to accomplish that is calling recursively a function that will loop over your list of words. 这是一个异步方案,一种实现方法是递归调用一个将遍历单词list的函数。 The recursion works according to each response from your server. 递归根据服务器的每个响应来工作。

Another approach is using Promise . 另一种方法是使用Promise

Look this code snippet (Recursion approach): 查看以下代码片段(递归方法):

//import the require library to make http requests to a server
const request = require('request');

//values to be sent via a restful GET request 
const list = [
  'value_one',
  'value_two'
];

//store resoonses from GET request
var listOfResponses = [];

//loop through the list
var loop = function(array, index, cb) {  
  if (index === array.length)
      cb();
      return;

  //Make a rest GET call to a server
  var url = 'http://notsurehowtomakethisworksoiamaskingstackoverflow.com/api/words/' + array[i];
  request(url, {
    json: true
  }, (err, res, body) => {
    if (err) {
      return console.log(err);
    }

    //store the response from the server into out array
    listOfResponses.push(body.response);
    loop(array, i++, cb);
  });
};

loop(list, 0, function() {
      /* ******************************* 
         HERE I WANT TO DO STUFF WITH listOfResponses ONCE ALL THE REQUESTS FINISH
       ********************************** */
});       

As you can see, the loop starts with a call to loop function with index = 0 and every response will call the loop function with an incremented index. 如您所见,循环从index = 0 loop函数调用开始,每个响应都将以递增的索引调用loop函数。

The recursion ends when index == list.length and the callback is executed to keep the flow of your logic. index == list.length时,递归结束,并且执行回调以保持逻辑流。

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

相关问题 使用axios的多个请求,而不必等待它们在数组列表中完成? - Multiple requests with axios without waiting for all of them to finish in an array list? 如何等到2个$ http请求以angularjs结尾 - How to wait until 2 $http requests end in angularjs 等到所有http GET请求完成后,再登录JS控制台 - Wait until all http GET requests done before logging to console in JS 如何等到多个 ajax 请求完成? - How to wait until multiple ajax requests are done? 等待所有请求完成 - Wait until all requests are completed 等到for循环中的所有Ajax请求都完成后再继续吗? - Wait until all Ajax requests in a for loop are done before moving on? 如何异步执行多个猫鼬查询并等到所有查询都执行完再发送响应? - How to execute multiple mongoose queries asynchronously and wait until all of them finish executing before sending response? 将多个 http.requests 中的 arrays 组合成一个数组 - Combining arrays from multiple http.requests into one array Google Maps Directions Service,如何等待所有请求完成? - Google Maps Directions Service, How to wait for all requests to finish? NodeJS 是否可以处理多个 https 请求并等到所有请求都解决 - NodeJS is it possible to handle multiple https requests and wait until all are resolved
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM