What I am trying to achieve here is to build a chart with the average SLA for each of the 4 regions. For this, I am calling an API to get some ids, I use these ids to call another API and get the SLAs. Then, I'm calculating the average SLA. I have to do this 4 times for each region. In the end, I want to have 2 arrays containing the region names and the average SLAs, so I can build the chart. Problem is, I can't get the SLA data out of these nested functions, so I can build the array. It tells me that the variables are undefined.
So the question is why can't I access the average
var as soon as I leave the function? I tried using return average;
. I also tried returning from both function(response)
and function(data)
. This is the first JS I write and I feel like there is something very wrong with it. Can you help me find out what?
// This is the fetch that gets me the SLAs and where I calculate the averages.
function regionsla(serviceids, regionName) {
fetch('api.php', {
// request body
}).then(
function(response) {
response.json().then(
function(data) {
var i = 0;
var sum = 0;
var labels = [];
var values = [];
for (const label in data.result) {
sum = sum + data.result[label].sla[0].sla;
i++;
}
average = sum / i;
labels.push(regionName);
values.push(average);
}
)
}
);
}
// This is the main function that runs in the beginning. The fetch is inside a for loop and it will get me the IDs that I need in order to run function regionsla.
async function get_sla() {
regionsids = [58, 59, 60, 61];
americaids = [];
europeids = [];
asiaids = [];
australiaids = [];
for (const regionid of regionsids) {
fetch('api.php', {
// request body
}).then(
function(response) {
response.json().then(
function(data) {
for (const label in data.result) {
switch (regionid) {
case 58:
americaids.push(data.result[label].serviceid);
break;
case 59:
australiaids.push(data.result[label].serviceid);
break;
case 60:
asiaids.push(data.result[label].serviceid);
break;
case 61:
europeids.push(data.result[label].serviceid);
}
}
switch (regionid) {
case 58:
regionsla(americaids, "America");
averageAmerica = average;
console.log(averageAmerica); //this returns
break; // average is not defined
case 59:
regionsla(australiaids, "Australia");
break;
case 60:
regionsla(asiaids, "Asia");
break;
case 61:
regionsla(europeids, "Europe");
}
})
}
);
}
}