Javascript - 异步等待和获取 - 返回值,而不是承诺?

Jun*_*Dev 2 javascript async-await

我正在尝试使用异步等待并使用 fetch api 获取数据

我的问题是,我只是不太明白我是如何真正从服务器得到答案的,而不是承诺的状态。我在控制台中得到以下信息

Promise {<pending>}
-------------------------------
{locale: "en"}
Run Code Online (Sandbox Code Playgroud)

但我更希望服务器响应应该是“locale: en”。

我的代码:

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


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();
}
Run Code Online (Sandbox Code Playgroud)

我想要存档的目标是,返回此“locale: en”响应并将其存储在我的代码示例开头的“locale”const 中。

韩国

TKo*_*KoL 5

您的函数应该更像这样:

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

您可以使用 await 在异步函数中使用该结果

const locale = await getLocale();
console.log(locale);
Run Code Online (Sandbox Code Playgroud)

或者通过使用 promise 方法

getLocale().then(function(locale){
    console.log(locale);
})
Run Code Online (Sandbox Code Playgroud)