0

I am trying to make request on dynamic URL-s from array and I have problem with accessing other global variables in request function. Here is example of my "not working" code

var body = '[{"id":"1","node_name":"kihinja","node_key":"2a55f8ecbdfa44f69ed5dee5842b21a5","server_url":"http:\/\/...","long_name":"Kuhinjski senzor","published":"1","check_string":"V6"},{"id":"2","node_name":"rasvjeta","node_key":"0f78f89eee9c481196db3f75691e7237","server_url":"http:\/\/...","long_name":"Stanje rasvjete","published":"1","check_string":"V1"}]';

var JSONObject = JSON.parse(body);
for (var key in JSONObject) {
if (JSONObject.hasOwnProperty(key)) {

    console.log(key); //outputs 0,1
    // prepare fetch urls according to their details
    var ftchNodeDetails = {
        method: 'GET',
        url: 'https://127.0.0.1:9443/' + JSONObject[key]["node_key"] + '/pin/' + JSONObject[key]["check_string"],
        method: JSONObject[key]["node_key"]
    };

    // run fetch for each node
    request(ftchNodeDetails, function (error, response, body) {
        if (error) throw new Error(error);
        console.log(JSONObject[key]["node_name"]);
        console.log(ftchNodeDetails.method); //prints same result for each key in loop
        console.log(key); //outputs 1,1

    }); // end request

   }
}

The thing is that keyvalue can not be printed inside request part. It can but it prints only max value of array. Why does it print out same values in request? Is there other more elegant way for this? Thanks.

Maka
  • 371
  • 3
  • 14

1 Answers1

0

Because the way closures work, by the time the fetch returns, your for loop has reached the last element. See here.

You can bind the specific value needed in each iteration. Something like this:

var ftchNodeDetails = {
        method: 'GET',
        url: 'https://127.0.0.1:9443/' + JSONObject[key]["node_key"] + '/pin/' + JSONObject[key]["check_string"],
method: JSONObject[key]["node_key"]
};

function wrapper(ftchNodeDetails) { 
  request(ftchNodeDetails, function (error, response, body) {
    if (error) throw new Error(error);
    console.log(JSONObject[key]["node_name"]);
    console.log(ftchNodeDetails.method);
    console.log(key); //outputs 1,1
  });
}(ftchNodeDetails);

Or, like JLRishe said, use let:

for (let key in JSONObject) {...}
Nick
  • 4,901
  • 40
  • 61
  • I have tried `request(ftchNodeDetails, myVariable, function (error, response, body) ` with passing myVariable but againt, it prints the same value. I am not that good, I have tried several things but non of them did not work :( – Maka Apr 04 '18 at 20:11
  • Thanks! `for (let key in JSONObject) {...}` worked. I'v just added `let` and it works now. Big thanks! – Maka Apr 04 '18 at 20:23