英文:
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 {<pending>}
-------------------------------
{locale: "en"}
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 "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();
}
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('/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();
}
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 => {
console.log(locale);
//locale is only valid here
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论