繁体   English   中英

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

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

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

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

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

但我更希望服务器响应应该是“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();
}

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

韩国

您的函数应该更像这样:

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

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

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

或者通过使用 promise 方法

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

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

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

好吧.. 如果我愿意,让我们假设,要从端点获取数据 (json) 并将其存储在变量中,我必须使用异步吗?

有没有其他方法可以同步获取数据?

暂无
暂无

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

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