【问题标题】:Using fetch, why do I need so many "await" statements?使用 fetch,为什么我需要这么多“等待”语句?
【发布时间】:2019-04-09 10:14:12
【问题描述】:

我在一个函数中有一条 fetch 指令,它从服务器获取 API 密钥,其他一些对象使用它来将该 API 密钥传递给需要它的任何服务。

export default async function getAPIKey(key) {
    return await (await fetch('http://localhost:8000/' + key)).json();
}

在我的天气对象中:

export default {
    URI: 'https://api.openweathermap.org',
    getLocalWeather: async function(city=null, countryCode=null) {
        try {
            // fetch the API key from environment
            const API_KEY = await getAPIKey('wx');
            //... rest of code

代码可以正常工作,但我不明白为什么我需要 3 个等待语句。我不是只需要两个吗?我需要一个用于getAPIKey() 中的fetch()。然后.json() 返回一个promise,因为它必须等待响应主体,所以我需要一个await 来调用getLocalWeather() 中的函数。但如果我在getAPIKey() 中没有两个等待,它只会返回[object Response]

基本上我想知道为什么以下错误:

export default async function getAPIKey(key) {
    return (await fetch('http://localhost:8000/' + key)).json();
}

在我的天气对象中:

export default {
    URI: 'https://api.openweathermap.org',
    getLocalWeather: async function(city=null, countryCode=null) {
        try {
            // fetch the API key from environment
            const API_KEY = await getAPIKey('wx');
            //... rest of code

我算错了吗?因为我只看到两个 Promise。我知道 async/await 函数是底层的承诺,所以 getAPIKey() 是一个承诺,但那个承诺不是 .json() 承诺吗?如果是这样,为什么我调用该函数的 await 不够?

我不确定我没有理解什么。

【问题讨论】:

  • 据我所知,无论您是从 async 函数返回值的承诺还是值(甚至是值的承诺),await 都应该给您价值。我想“为什么以下是错误的”实际上并没有错;当你运行它时会发生什么?因为它不可能产生 Response 对象 - Responsefetch 承诺的值;如果您在其上运行json,它将给您一个json 承诺,或者响应是JSON 编码的任何值;我不知道会在哪种情况下运行 .json() 而你最终得到 Response

标签: async-await es6-promise fetch-api


【解决方案1】:

您不需要getAPIKey() 中的任何await 语句,您的函数甚至不需要是async。你可以这样做:

export default function getAPIKey(key) {
    return fetch('http://localhost:8000/' + key).json();
}

你只想从fetch().json()返回承诺。

代码可以正常工作,但我不明白为什么我需要 3 个 await 语句。我不是只需要两个吗?

其实,await getAPIKey() 时只需要一个。 getAPIKey() 里面的其他人根本不需要。


当您执行以下操作时:

export default async function getAPIKey(key) {
    return await fetch('http://localhost:8000/' + key).json();
}

您只是添加了一个没有任何好处的多余await。该函数返回一个promise(所有async 函数都返回一个promise)并且当await 完成时该promise 被解决,这与首先执行return fetch('http://localhost:8000/' + key).json(); 完全相同。添加第二个await 也没有任何价值。

【讨论】:

    猜你喜欢
    • 2022-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 2020-09-12
    • 2012-08-24
    • 2013-07-11
    相关资源
    最近更新 更多