我试图在foreach循环中从axios请求中获取数据,但是每次都未定义时。如果将console.log移动到.then函数中,则可以运行,但是在循环之后,它将返回空数组。我确实发现,它在保存到数组之前正在重新进入循环。我该如何解决?
var temp = [];
for(var route of coordinates) {
axios('https://api.openweathermap.org/data/2.5/weather?lat=' + route.position.latitude + '&lon=' + route.position.longitude + '&units=metric&appid=39f1004c7ecc22d6f734974c44428625')
.then((response)=>{
temp.push({lat: route.position.latitude, lon: route.position.longitude, temp: Math.round(response.data.main.temp)});
})
.catch((error)=>{
console.log(error)
})
}
console.log(temp);
答案 0 :(得分:0)
尝试阅读并理解以下内容:
(https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Introducing)
temp
,直到最后一次迭代中的最后一个axios响应为止。
var temp = [];
let idx = coordinates.length;
for (var route of coordinates) {
axios('https://api.openweathermap.org/data/2.5/weather?lat=' + route.position.latitude + '&lon=' + route.position.longitude + '&units=metric&appid=39f1004c7ecc22d6f734974c44428625')
.then((response) => {
temp.push({ lat: route.position.latitude, lon: route.position.longitude, temp: Math.round(response.data.main.temp) });
// if this is the last iteration show temp
if (!--idx) {
console.log(temp);
}
})
.catch((error) => {
console.log(error)
})
}
// this won't wait for axios calls so temp is empty
console.log(temp);