繁体   English   中英

为什么我的异步 function 总是返回待处理的 promise?

[英]Why does my async function always return a pending promise?

当我 console.log(data) 时,我记录了我需要的信息,但是如果在 getWeather() 中返回数据的值,它只会返回一个挂起的 promise。 我尝试了很多东西,但到目前为止都没有奏效。 我将在下面留下我损坏的代码。

const axios = require('axios');
const getWeather = async () => {
    try {
        let response = await axios.get(
            'http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}'
        );

        let data = response.data;
        return data;
    } catch (e) {
        console.log(e);
    }
};

async function returnAsync() {
    const x = await getWeather();
    return x;
}
console.log(getWeather()); // returns a pending promise
console.log('check ', returnAsync()); // also returns a pending promise

async函数必须返回 promise。 (他们隐式返回Promise<void>而不是void !)

异步函数总是返回 promise。 如果异步 function 的返回值不是显式 promise,它将隐式包装在 promise 中。

例如,以下内容:

 async function foo() { return 1 }

...相当于:

 function foo() { return Promise.resolve(1) }

资源

//const getWeather = async () => {...

异步函数的返回值将是 Promise,它将使用异步 function 返回的值解析,或者被异步 ZC1C425268E17385D1AB504F14F 抛出的异常或未捕获的异常拒绝。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function查看更多信息

这可能与您尝试在同步 function 内部调用异步 function 的事实有关。 这是一个很常见的错误,所以不要担心。 通常,如果您考虑结构,从技术上讲,控制台日志可以在异步 function 完成之前运行。 这就是为什么我们有“回调函数”,它基本上只在异步返回值时运行。

Axios 有一个非常巧妙的方法来使用这些回调,它只是使用 .then .then() function。

所以试试这个,看看它是否有效:

const axios = require('axios');
const getWeather = async () => {
    axios.get('http://api.openweathermap.org/data/2.5/forecast?id=524901&appid={apiKey}')
    .then(json => console.log(json))
    .catch(error => console.log(error))
};

getWeather();

因为您尝试在异步 function 中调用 get 请求,所以您无法在同步 function 中获取数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM