0

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)?

DrakaSAN
  • 7,673
  • 7
  • 52
  • 94
Christian68
  • 845
  • 4
  • 13
  • 24
  • Possible duplicate of [async for loop in node.js](http://stackoverflow.com/questions/21184340/async-for-loop-in-node-js) – DrakaSAN Sep 28 '16 at 14:14
  • You can use control flow library like `async`, or use recursion to do that. Promises also would work. – DrakaSAN Sep 28 '16 at 14:15
  • Thanks - yes, just saw this which I believe does solve the problem: https://github.com/caolan/async/blob/v1.5.2/README.md#whilst – Christian68 Sep 28 '16 at 14:27

1 Answers1

0

First of all please check x-forwarded-for lies in response and if the same problem persists as you are expecting(asynchronous call) then just wrap this call inside a anonymous function like this

while(i > 0) {
    (function abc(){
        client.methods.reflect(function (data, response) {
            console.log("x-forwarded-for: " + data.headers["x-forwarded-for"]);
            // raw response
            //console.log(response);
        });
    }())

    i--;
}
Atul Agrawal
  • 1,474
  • 5
  • 22
  • 41