Linked Questions

Popular Questions

Making a dynamic number of requests with sequential parameters

Asked by At

I'm building an application in which I need to make sequentially numbered requests starting with a specified number. This is my first node.js project so I'm learning as I go but I'm stuck on this particular issue.

I need to pass along the id so that I can reference it later. Essentially, I need to use the data from the first request to make a second request to a different api. Most of the data made to the second request will come from the response of the first request but the id does not so I need to pass it along somehow.

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

var id = process.argv[2];
var numIterations = process.argv[3] || 5;
var apiRequests = [];

for (var i = 0; i < numIterations; i++) {
    var requestDetails = {
        uri: 'https://www.example.com/id=' + id,
        json: false
    };

    apiRequests.push(
        rp(requestDetails).then(
            function (data) {
                return {
                    id: id,
                    html: data 
                };
            }
        )
    );

    id++;
}

Promise.all(apiRequests)
    .then((results) => {
        for (var i = 0; i < results.length; i++) {
            console.log(results[i].id); continue;
        }
    }).catch(err => console.log(err));

If id = 1 and numIterations = 5 for example, then I would expect to see: 1 2 3 4 5

But instead I see: 5 5 5 5 5

I get why this happens because of how request-promise works but I'm not sure how best to resolve it.

Related Questions