Populating request promise uri with for loop index

2542 views javascript
-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 shoes 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?

answered question

1 Answer

9

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

posted this

Have an answer?

JD

Please login first before posting an answer.