这个问题可能不是关于一个实际的问题,尽管我还是很好奇这里发生了什么。
const r = Promise.resolve('I resolved')
.then(() => {
console.log('*****then*****')
console.log( r )
console.log('*****then*****')
})
setTimeout(() => {
console.log('*****setTimeout*****')
console.log( r )
console.log('*****setTimeout*****')
})
/*
logs:
*****then*****
Promise { <pending> }
*****then*****
*****setTimeout*****
Promise { undefined }
*****setTimeout*****
*/
在.then处理程序中,我特意不想将我从已解决的承诺中得到的结果注销,这将是一个典型的用例,我对承诺本身的实际价值感到好奇。
我认为发生的情况是这样的:r不是Promise.resolve()的值,因为.then会返回一个新的承诺。如果我在Timers阶段把它的值记录出来,那是在.then处理程序完成之后,所以它记录出来的承诺解析为'undefined',因为没有任何显式返回。
但是为什么r的值还在.then处理程序中待定呢?是因为.then处理程序还没有执行完吗?
是不是因为.then处理程序还没有执行完?
是的。r
承诺将与该回调函数的返回值一起解析,所以在它完成执行之前,它不能被履行,因此必须是仍然待定。
这就是你想要的。
你不要把解析的值传递给.then()函数。或者返回它。当返回一个承诺时。你需要一个带有 await 的异步函数。await评估承诺并提取值。
(async function () {
const r = await Promise.resolve("I resolved")
.then((r) => {
console.log("*****then*****");
console.log(r);
console.log("*****then*****");
return {
r,
text: "this works",
remember: "use async/await to resolve promises",
};
})
.catch((err) => console.log(err));
setTimeout(() => {
console.log("*****setTimeout*****");
console.log(r.r, r.text, r.remember);
console.log("*****setTimeout*****");
}, 1000);
})();