1

I have a series of request that I would like to call in a for-loop.

The only thing I am changing in the endpoint is an index parameter. This index parameter should be the same as the index of for-loop(0-100).

However the promise return values are all the same response from one of the endpoints. (i.e. all the return values are what I would expect from ${someEndPoint}?index=61).

someIndex = 100
var promises = [];

for (var i = 0; i < someIndex; i++){
    var options = {
        method: 'GET',
        uri: `${someEndPoint}?index=${i}`,
        json: true
    }
    promises.push(request(options))
}
Promise.all(promises).then(function(values){
    console.log(values) // returns array of 100 of the same responses.
}).catch(e => {
    console.log(e)
});

P.S. I'm using a node.js server, and it shows that my server has made all 100 of the correct GET calls, but the values object has only been populated with one specific request response multiple times.

[{ index: 70, data: '...' },
{ index: 70, data: '...' },
...
{ index: 70, data: '...' },
{ index: 70, data: '...'} ]

How am I suppose to get the correct responses?

J.Ting
  • 95
  • 2
  • 10
  • 1
    The code you posted should not have that problem so if that's the code causing your problem then it's probably the `request` method doing something wrong. You could simplify the code by using [map](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map) `Promise.all([...new Array(100)].map((_,i)=>i).map(i=>request(...i)).then(result=>...)` – HMR Nov 09 '18 at 07:47
  • 1
    I just checked it was something wrong with the endpoint I called (I wrote that too). In case other's run into the same problem, it was because I missed a `var` in my code, which made some variables global. Found a similar issue on github: https://github.com/request/request-promise/issues/212. – J.Ting Nov 09 '18 at 10:33

1 Answers1

0

You should use async await in this loop. You should also explore closure and other concepts.

You are getting same index response, because you are not waiting for each response.

Explore async await.

SomeLinks:

Using async/await with a forEach loop

https://dev.to/kayis/await-your-loops-680

https://medium.com/@antonioval/making-array-iteration-easy-when-using-async-await-6315c3225838

Rishi Shah
  • 46
  • 6
  • No, using await will make the requests in serie, not parallel. There is also nothing wrong with the code in the question (apart from over complicating it using loops) – HMR Nov 09 '18 at 07:49