Javascript 如何在不执行其余代码的情况下接收承诺的值?我得到[目标,目标]
此函数应返回“HomeStack” 当我这样做时:Javascript 如何在不执行其余代码的情况下接收承诺的值?我得到[目标,目标],javascript,Javascript,此函数应返回“HomeStack” 当我这样做时: console.log(getSessionPrevious ); 返回: Promise { "_40": 0, "_55": null, "_65": 0, "_72": null, } 如何才能得到这个承诺的结果 首先,您需要添加括号来实际调用函数。然后您需要使用wait调用函数来实际等待返回值。由于只能在async函数中使用await,请为此声明
console.log(getSessionPrevious );
返回:
Promise {
"_40": 0,
"_55": null,
"_65": 0,
"_72": null,
}
如何才能得到这个承诺的结果 首先,您需要添加括号来实际调用函数。然后您需要使用
wait
调用函数来实际等待返回值。由于只能在async
函数中使用await
,请为此声明一个函数
async function Demo()
{
console.log(await getSessionPrevious());
}
Demo();
// Code here will be executed before Demo() is actually executed because we are not awaiting it.
请注意,添加异步代码(如async/await或使用普通承诺)是有传染性的。如果要处理结果,必须支持调用堆栈中所有调用的异步性质。这在以下主题中得到了很好的解释:
然后,catch
:
getSessionPrevious()。然后(值=>{
console.log(“上一个会话”,值);
}).catch(错误=>{
log(“获取上一个会话时出错”,错误);
});
也可以使用封装的匿名异步函数:
(异步()=>{
试一试{
常量值=等待getSessionPrevious();
console.log(“上一个会话”,值);
}捕获(错误){
log(“获取上一个会话时出错”,错误);
}
})();
您没有等待解析getSessionPrevious
函数。您需要一个wait
关键字:<代码>控制台.log(等待getSessionPrevious)代码>它导致错误你能描述一下错误是什么吗?@Nicolas i.imgur.com/4h1pHxq.jpgmaybe会帮助你的。
async function Demo()
{
console.log(await getSessionPrevious());
}
Demo();
// Code here will be executed before Demo() is actually executed because we are not awaiting it.