Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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

//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
********************************** */
like image 755
user2924127 Avatar asked Dec 05 '25 14:12

user2924127


1 Answers

Just map it to an array of promises:

  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(promises).then(results => {
  //...
 });
like image 125
Jonas Wilms Avatar answered Dec 08 '25 02:12

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!