如何从Node.js中的异步axios请求中获取数据

时间:2020-01-10 16:04:42

标签: node.js

我试图在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);

1 个答案:

答案 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);