【问题标题】:Why does my async function always return a pending promise? [duplicate]为什么我的异步函数总是返回一个未决的承诺? [复制]
【发布时间】:2021-05-08 08:02:37
【问题描述】:

当我使用 console.log(data) 时,我会记录我需要的信息,但如果在 getWeather() 中返回 data 的值,它只会返回一个待处理的 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; await 表达式 always 会产生 Promise。
  • 你需要将console.loginsidereturnAsync函数,并记录x

标签: javascript async-await axios


【解决方案1】:

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

异步函数总是返回一个承诺。如果异步函数的返回值不是显式的 Promise,它将被隐式包装在 Promise 中。

例如:

async function foo() {
   return 1
}

...等价于:

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

Source

【讨论】:

  • 只是评论,JS没有void的概念。你可能从 TS 那里得到这个
  • @ChayimFriedman 是的,我一个 TS 开发者,指定 undefined 会更好吗?
  • 没问题,我只是想对未来的访客说这些
【解决方案2】:

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

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

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

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();

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

【讨论】:

  • 我明白了,但是如何将 API 中的数据存储在另一个变量中?我将不得不在程序的另一部分使用这些数据。
  • 所以规则是你可以在异步函数内部运行同步函数,反之则不行。所以通常你想围绕异步函数来定位你的程序,它会让生活变得更容易。因此,如果您有另一个函数来使用数据,我会从异步函数回调(.then() 位)内部运行该函数,该函数只有在检索到数据后才会运行
【解决方案3】:

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

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

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

【讨论】:

    猜你喜欢
    • 2020-01-11
    • 1970-01-01
    • 2021-08-01
    • 1970-01-01
    • 2021-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    相关资源
    最近更新 更多