为什么承诺的状态'pending'如果在执行期间注销其处理程序?



这个问题可能不是关于实际问题,尽管我仍然很好奇这里发生了什么:

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 返回一个新的承诺。如果我在计时器阶段注销该值,那是在 .then 处理程序完成后,因此它会注销解析为"未定义"的承诺,因为没有明确返回任何内容。

但是为什么 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);
})();

最新更新