As a beginner in JavaScript, I wrote some code to fetch URLs using the fetch API. However, I encountered an issue with my code where it says Functions declared within the loop are referencing an outer scoped variable. I understand that this is because of the outer scope of the obj variable, but I'm unsure how to fix it. Please assist me. Here's the code snippet:
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))
}
The expected output should display as follows: (values of Id and descr will depend on the 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"}]