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 key
value 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.