簡體   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