如果在执行它的处理程序期间注销,为什么 promise 的状态是 'pending'?
Why is the state of a promise 'pending' if logged out during executing it's handler?
这个问题可能不是一个实际问题,虽然我仍然很好奇这里发生了什么:
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 returns 是一个新的承诺。如果我在 Timers 阶段注销该值,它是在 .then 处理程序完成之后,因此它会注销一个解析为 'undefined' 的承诺,因为没有明确返回任何内容。
但为什么 r 的值仍然在 .then 处理程序中悬而未决?是不是.then handler没有执行完?
Is it because that the .then handler hasn't finished executing?
是的。 r
promise 将使用该回调函数的 return 值来解决,因此在它完成执行之前无法实现,因此必须仍处于待定状态。
这就是你想要的。
您没有将解析后的值传递给 .then() 函数。或者return吧。当 return 承诺时。您需要一个带等待的异步函数。 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);
})();
这个问题可能不是一个实际问题,虽然我仍然很好奇这里发生了什么:
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 returns 是一个新的承诺。如果我在 Timers 阶段注销该值,它是在 .then 处理程序完成之后,因此它会注销一个解析为 'undefined' 的承诺,因为没有明确返回任何内容。
但为什么 r 的值仍然在 .then 处理程序中悬而未决?是不是.then handler没有执行完?
Is it because that the .then handler hasn't finished executing?
是的。 r
promise 将使用该回调函数的 return 值来解决,因此在它完成执行之前无法实现,因此必须仍处于待定状态。
这就是你想要的。
您没有将解析后的值传递给 .then() 函数。或者return吧。当 return 承诺时。您需要一个带等待的异步函数。 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);
})();