【发布时间】:2022-01-03 13:40:07
【问题描述】:
我在这里想要实现的是为 4 个区域中的每一个构建一个包含平均 SLA 的图表。为此,我调用一个 API 来获取一些 id,我使用这些 id 来调用另一个 API 并获取 SLA。然后,我正在计算平均 SLA。我必须为每个地区做 4 次。最后,我想要 2 个包含区域名称和平均 SLA 的数组,这样我就可以构建图表。问题是,我无法从这些嵌套函数中获取 SLA 数据,因此我可以构建数组。它告诉我变量是未定义的。
所以问题是为什么我一离开函数就不能访问average var?我尝试使用return average;。我还尝试从function(response) 和function(data) 返回。这是我写的第一个 JS,我觉得它有很大的问题。你能帮我看看是什么吗?
// 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");
}
})
}
);
}
}
【问题讨论】:
-
奇怪的抓取。这是规范获取:
fetch('api.php') .then(response => response.json()) .then(data => console.log(data)); -
这是个坏主意:
for (const regionid of regionsids) { fetch('api.php', {...).then(永远不要循环 ajax。而是将下一个调用放在成功或完成的提取中 -
最后一个带有平均值的 reduce 会更容易阅读
-
但是获取一个区域 id 然后切换听起来也很混乱。为什么不
let americaids = []; fetch (api.php?region=58)。但如果是你的 api,那么一次调用它们就足够了
标签: javascript arrays function