JavaScript – Async await and fetch – 返回值,而不是Promise?

huangapple go评论95阅读模式
英文:

Javascript - Async await and fetch - return the value, not the promise?

问题

我正在尝试使用async await和fetch api来获取数据。

我的问题是,我不太明白如何真正从服务器获取答案而不是promise的状态。我在控制台中看到以下内容:

Promise {<pending>}
-------------------------------
{locale: "en"}

但我更希望看到的是服务器响应,应该是"locale: en"。

我的代码如下:

const locale = getLocale();
console.log(locale) // 这里我希望输出"locale: en"

async function fetchLocale() {
    return await fetch('/get-language', {
        headers: {
            'Accept': 'application/json'
        },
        method: 'GET',
    }).then(response => {
        if (response.ok) {
            return response.json()
        }
        return Promise.reject(Error('error'))
    }).catch(error => {
        return Promise.reject(Error(error.message))
    })
}

async function getLocale() {
    return await fetchLocale();
}

我想要实现的目标是,在我的代码示例开头返回"locale: en"响应并将其存储在"locale"常量中。

英文:

I'm trying to work with async await and fetching data using the fetch api

My problem is, I just don't quite understand how I really get the answer from the server and not the status of the promise. I get the following in the console

Promise&#160;{&lt;pending&gt;}
-------------------------------
{locale: &quot;en&quot;}

but what I rather expect is the server response which should be "locale: en".

my code:

const locale = getLocale();
console.log(locale) // here I want to have &quot;locale: en&quot; as a output


async function fetchLocale() {
    return await fetch(&#39;/get-language&#39;, {
        headers: {
            &#39;Accept&#39;: &#39;application/json&#39;
        },
        method: &#39;GET&#39;,
    }).then(response =&gt; {
        if (response.ok) {
            return response.json()
        }
        return Promise.reject(Error(&#39;error&#39;))
    }).catch(error =&gt; {
        return Promise.reject(Error(error.message))
    })
}

async function getLocale() {
    return await fetchLocale();
}

The goal I want to archive is, to return this "locale: en" response and store it in the "locale" const at the beginning of my code example.

KR

答案1

得分: 9

async function getLocale() {
let response = await fetch('/get-language', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
method: 'GET',
});
// 在这里可以检查response.ok,如果需要,可以直接抛出错误
return await response.json();
}

并且你可以在异步函数中使用await来消耗这个结果:

const locale = await getLocale();
console.log(locale);

或者使用Promise方法:

getLocale().then(function(locale){
console.log(locale);
})

英文:

Your function should look more like this:

async function getLocale() {
    let response = await fetch(&#39;/get-language&#39;, {
        headers: {
            &#39;Accept&#39;: &#39;application/json&#39;,
            &#39;Content-Type&#39;: &#39;application/json&#39;
        },
        method: &#39;GET&#39;,
    });
    // you can check for response.ok here, and literally just throw an error if you want
    return await response.json();
}

And you can consume the result of that in an async function using await

const locale = await getLocale();
console.log(locale);

or by using the promise methods

getLocale().then(function(locale){
    console.log(locale);
})

答案2

得分: 4

要获取Promise解析后的值而不是Promise本身,请使用.then()await。请注意,这两者都需要一个回调函数或异步上下文,因为将此异步结果带入同步上下文(例如文件的顶层)是不可能的。

getLocale().then(locale => {
    console.log(locale);
    // 只有在这里locale是有效的
});
英文:

To get the value a Promise resolves with and not the promise itself, use .then() or await. Note that both require a callback or asynchronous context as it's simply not possible to bring this asynchronous result to a synchronous context such as the top level of your file.

getLocale().then(locale =&gt; {
    console.log(locale);
    //locale is only valid here
});

huangapple
  • 本文由 发表于 2020年1月4日 01:25:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59582780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定