0

I am trying to write a code as follows -

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

var myArr = [0,1,2,3,4,5];
var a = 0;
for( var i in myArr) {
  rp('someURL?q='+myArr[i])
  .then(function (response) {
      myArr[i] = response;
  });
}
return myArr;

How can I wait for each request then proceed the for loop for next iteration and in the end return myArr?

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Abhigyan Singh
  • 137
  • 3
  • 14
  • You're getting the same request? – NoobTW Aug 27 '18 at 12:12
  • You really should look at using Promise.all(). As @NoobTW mentioned though, you are calling the same request on each iteration and storing the same result in each array index. Does the request change in some other manner between calls or does the response change on the server at random? – musicfuel Aug 27 '18 at 12:15
  • Yep, I can give you an example with Promise.all if you're calling different requests. – NoobTW Aug 27 '18 at 12:16
  • In any case though, you will always be returning a promise, never a array. – Ayush Gupta Aug 27 '18 at 12:18
  • I have updated the question body. Can't use Promise.all as it needs to be run in serial. An example will be nice. Thanks everyone – Abhigyan Singh Aug 27 '18 at 12:21
  • Why would you need to wait for each request to be processed? It doesn't look like a subsequent request relies on a previous request. You could process them all at the same time. – Adam Jenkins Aug 27 '18 at 12:24
  • Actually actual code is quite big. So this is just a skeleton and the final response does depend on every subsequent request. – Abhigyan Singh Aug 27 '18 at 12:27

1 Answers1

-1

If you can send request all at the same time, you can use Promise.all.

Promise.all(myArr.map(function(q){ return rp('someURL?q='+q); })
    .then(function(res){
        console.log(res);
        // here's all the requests.
    });
NoobTW
  • 2,466
  • 2
  • 24
  • 42