我有一个关于for循环的问题,因为如果在异步功能中使用它,则不会进入循环。这是我的代码:
const selectedData = [
{ id: "2468005", name: "468005 (2012 XD112)" },
{ id: "2004953", name: "4953 (1990 MU)" }
];
const minDate = new Date("1900-01-01");
const maxDate = new Date("1999-12-31");
async function getDataForChart() {
let chartingData = [];
selectedData.forEach(element => {
let url = `someurl`;
fetch(url)
.then(res => res.json())
.then(data => {
const filteredDates = data.close_approach_data.filter(obj => {
let checkDate = new Date(obj.close_approach_date);
return checkDate > minDate && checkDate < maxDate;
});
chartingData.push({
name: element.name,
itterations: filteredDates.length
});
});
});
return chartingData;
}
(async () => {
const dataSet = await getDataForChart();
console.log(dataSet);
let labels = [];
let itterationData = [];
let backgroundColor = [];
/**
* set specific data for each selected element
*/
dataSet.forEach(data => {
if (data.itterations < 25) {
labels.push(data.name);
itterationData.push(data.itterations);
backgroundColor.push("green");
} else if (data.itterations < 45) {
labels.push(data.name);
itterationData.push(data.itterations);
backgroundColor.push("yellow");
} else if (data.itterations < 75) {
labels.push(data.name);
itterationData.push(data.itterations);
backgroundColor.push("orange");
} else if (data.itterations >= 75) {
labels.push(data.name);
itterationData.push(data.itterations);
backgroundColor.push("red");
}
});
})();
我也尝试了for / of循环,但还是一样。它记录我需要的数据,但不会运行循环。知道如何解决这个问题吗?