gpt4 book ai didi

javascript - 返回已解决的 promise 值

转载 作者:行者123 更新时间:2023-12-01 16:18:10 28 4
gpt4 key购买 nike

  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 {<resolved>: "yikes"}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "yikes"

我只想要 promiseValue 而不是它周围的所有东西。我该怎么做呢?

最佳答案

async 函数立即返回一个 promise,无需等待 promise 解决。您可以在函数内改为使用 console.log:

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

关于javascript - 返回已解决的 promise 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60240476/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com