I'm beginner to a JavaScript. I developed one code to fetch some URLs output using fetch API. When I used below code it says, Functions declared within the loop is referencing an outer scoped variable. I understand that it is due to outer scope of obj variable but how can I make it work. Kindly help. Below is the code,
var obj = [
{"Id":"10101","descr":"server1.com"},
{"Id":"10102","descr":"server2.com"},
{"Id":"10103","descr":"server3.com"},
{"Id":"10104","descr":"server4.com"},
{"Id":"10105","descr":"server5.com"},
{"Id":"10106","descr":"server6.com"},
{"Id":"10107","descr":"server7.com"}
];
var temp = [];
for (var i = 0; i < obj.length; i++){
var id = obj[i].Id;
fetch('https://abced.com/api/'+id+'/value', {
method : "GET",
headers: { "Authorization": "xyz" }
})
.then(res => res.json())
.then(data => {
var stats = data.status;
if (stats != "OK") {
temp.push({ Id: obj[i].Id, descr: obj[i].descr, value:"ERROR" });
}
console.log(temp);
})
.catch(x => console.log("fail:", x))
}
My expected output is. (values of Id and descr will depends on if statement in the code)
[{"Id": "10101","descr": "server1.com","status": "ERROR"},
{"Id": "10103","descr": "server3.com","status": "ERROR"},
{"Id": "10104","descr": "server4.com","status": "ERROR"}]