I'm using node-rest-client
to make a GET call to an endpoint, and would like to make this call multiple times (in a loop), then expose a parameter of the response.
The code looks like:
// registering remote methods
client.registerMethod("reflect", "<the URL>", "GET");
// call the method
var i = 10;
while (i>0) {
client.methods.reflect(function (data, response) {
console.log("x-forwarded-for: " + data.headers["x-forwarded-for"]);
// raw response
//console.log(response);
});
i--;
}
The error I get is:
TypeError: Cannot read property 'x-forwarded-for' of undefined
If i
is equal to 2, then this is OK.
I suppose the issue comes from the fact that this is asynchronous execution and all the calls in the while are fired at once, resulting into some clogging somewhere along the lines.
What is the best way of having a synchronous execution (assuming this is where the problem lies)?