【问题标题】:How to get data out of async axios request in Node.js如何从 Node.js 中的异步 axios 请求中获取数据
【发布时间】:2020-01-11 00:41:17
【问题描述】:

我正在尝试从 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);

【问题讨论】:

标签: node.js


【解决方案1】:

尝试阅读并理解以下内容:
(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);

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2019-11-26
    • 2021-01-25
    • 2020-09-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多