-2

I have below code which is making an third party api call using request npm

const array = []
for (var i = 0; i < 10; i++) {
  request('api_call', function(err, res) {
    array.push(res)
  })
}
console.log(array)

But didn't get anything in the array.

Can someone please help how can I wait for all the 10 api calls?

Dark Knight
  • 995
  • 4
  • 22
  • 48

1 Answers1

1

request() is non-blocking and asynchronous. So your for loop runs to the end, before ANY of your request() calls have completed. There are many ways to do this, but the best way I know of is to use promises and Promise.all():

const rp = require('request-promise');
const promises = [];

for (var i = 0; i < 10; i++) {
  promises.push(rp('api_call'));
}
Promise.all(promises).then(results => {
   console.log(results);
}).catch(err => {
   console.log(err);
});

request-promise is a promisified version of the request library (returns a promise instead of using a plain callback). This code accumulates promises into an array and then uses Promise.all() to tell us when all the promises have resolved (e.g. all the requests are done). The results are then presented to us in order in the results array.

This method run all your requests in parallel.


If you want to run them in sequence instead of in parallel, you can use async/await to make the for loop pause for each result before continuing.

const rp = require('request-promise');

async function myFunc() {
    const results = [];
    for (let i = 0; i < 10; i++) {
        let r = await rp('api_call');
        results.push(r);
    }
    return results;
}


myFunc().then(results => {
   console.log(results);
}).catch(err => {
   console.log(err);
});

If you're actually not just sending the same request 10 times, but are actually iterating an array to make the 10 api calls, then you'd probably use .map() or something like that.

jfriend00
  • 683,504
  • 96
  • 985
  • 979