Javascript 返回解析承诺值
我有此获取请求,但当我记录结果时,我看到的是:Javascript 返回解析承诺值,javascript,promise,Javascript,Promise,我有此获取请求,但当我记录结果时,我看到的是: const displayCharacters = async () => { if(filteredCharacters !== 'default'){ const a = filteredCharacters.map(e => e.name); const options = { method: "POST", headers: { "Content-Type"
const displayCharacters = async () => {
if(filteredCharacters !== 'default'){
const a = filteredCharacters.map(e => e.name);
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 'data' : a })
};
const b = await fetch("/image",options).then(res => res.json())
return b;
}else{
return "yikes";
}
}
console.log(displayCharacters());
Promise{:“yikes”}
__承诺
[[PromiseStatus]]:“已解决”
[[PromiseValue]]:“yikes”
我只想要承诺的价值,而不是它周围的一切。我该怎么做 函数的
async
会立即返回一个承诺,而无需等待承诺的解析。您可以改为在函数中使用console.log:
Promise {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"
我所知道的使用fetch的最佳方法如下:
const displayCharacters = async () => {
if(filteredCharacters !== 'default'){
const a = filteredCharacters.map(e => e.name);
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 'data' : a })
};
try {
const b = await fetch("/image",options).then(res => res.json());
console.log(b);
//the better practice is however, to do like:
const b = await fetch("/image",options)
const result = await b.json();
console.log(result );
}
catch(err) {
console.log(err);
}
}else{
console.log("yikes");
}
}
displayCharacters();
基本上,你连两个THEN和一个catch来完全理解响应
-然后,首先检查api级别的错误
-第二步,然后获取数据
-catch在无法访问api本身时调用,就像连接问题一样您不能。异步函数总是返回承诺。要么调用.then函数,要么将代码放入异步函数中,等待承诺。
displayCharacters()。然后(data=>console.log(data))
这就是它的工作方式async
会“立即返回承诺”,但更重要的是,它允许代码直接从异步函数(如fetch()
)返回响应,而无需回调。await
表达式允许在异步函数中继续执行之前等待fetch()
调用的响应。注意:您将希望处理未捕获的异常,因为wait最好不要将请求包装在try…catch
中@segFault,谢谢你的建议,我的本意是通过保持代码简单来回答他的具体问题,但你是对的,值得一提。
const displayCharacters = async () => {
if(filteredCharacters !== 'default'){
const a = filteredCharacters.map(e => e.name);
const options = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ 'data' : a })
};
const b = await fetch("/image",options)
.then(res => {
// Handle API Errors
if (!res.ok) {
throw Error(res.statusText);
}
// Return if no errors
return res.json();
})
// this is the data you want
.then(data => data)
// it will only reject on network failure or if anything prevented the request from completing
.catch(error => {
console.log(error.message)
});
return b;
}else{
return "yikes";
}
}