我正在尝试使用异步等待并使用提取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中。
KR
答案 0 :(得分:3)
要获取Promise所解析的价值而不是Promise本身,请使用=MONTH(A2)=MONTH(TODAY())
或.then()
。请注意,两者都需要回调或异步上下文,因为根本不可能将此异步结果带到同步上下文(例如文件的顶层)。
await
答案 1 :(得分:2)
您的函数应如下所示:
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);
})