then() 和 catch() 返回 Promises,指向内存中的同一个实例

问题描述 投票:0回答:1

疑问:

根据 MDN 文档,then() 和 catch() 立即返回一个 Pending Promise,如果处理函数不返回任何内容,则返回的 Promise 会以未定义的值实现。因此,如果当前 Promise 是 P0,则 then()(附加到 P0)返回 Promise P1,而 catch()(也直接附加到 P0)返回 Promise P2。最初 P1 和 P2 都处于“待处理”状态。现在,如果 catch() 的处理程序运行,P2 将获得未定义的值。既然 then() 的处理程序永远不会运行,P1 是否会始终处于“挂起”状态?如果没有,那么为什么它的状态会改变以及它是如何改变的? (改变状态的代码控制流程是怎样的)

代码:

const p0 = new Promise((resolve,reject) => {
    let num = Math.random();
    setTimeout(()=> {
        if(num >= 0.5) {
            console.log("Resolved");
            resolve("Promise resolved");
        }
        else {
            console.log("Rejected");
            reject("Promise rejected");
        }   
    }, 7000);
});

const p1 = p0.then(function (resolveValue) {
    console.log("Then handler was executed");
    console.log(resolveValue);
})
console.log("P1");
console.log(p1);

const p2 = p0.catch((rejectValue) => {
    console.log("Catch handler was executed");
    console.log(rejectValue);
})
console.log("P2");
console.log(p2);
setTimeout(()=> {
    console.log("P1");
    console.log(p1);
}, 12000);
setTimeout(()=> {
    console.log("P2");
    console.log(p2);
}, 17000);

输出:

P1

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined

P2

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "pending"
[[PromiseResult]]: undefined

Rejected
Catch handler was executed
Promise rejected

Uncaught (in promise) Promise rejected
Promise.then (async)        
(anonymous) @   app2.js:15

P1 
Promise {<rejected>: 'Promise rejected'}
[[Prototype]]: Promise
[[PromiseState]]: "rejected"
[[PromiseResult]]: "Promise rejected"

P2
Promise {<fulfilled>: undefined}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: undefined
javascript asynchronous ecmascript-6 promise callback
1个回答
0
投票

JS Promise 是一个由 Web-API 处理的异步函数,其 then()catch() 方法仅在 Promise resolvedrejected 时才起作用 [最终当 resolve() 时/reject()方法被调用]。主要与

async-await
功能类似。

您在 Promise 中添加了 7 秒的 setTimeout 以使其解析/拒绝。

因此,最初,当您尝试打印 P1P2 时,两者都会转发相同的 P0 承诺。因此,同时调用 P0,如果尝试打印 P1 和 P2 值,它将处于待处理状态[取决于事件处理程序何时调用异步函数]。

7秒后,你可能会得到下面的结果。

Rejected
Catch handler was executed
Promise rejected

最后,当您在一定时间后再次打印下面的内容时, 它会给你它的最后状态

then() 方法被拒绝为

Promise {<rejected>: 'Promise rejected'}
并且 catch() 被实现为
Promise {<fulfilled>: undefined}
[打印哪一个承诺将被实现]。

如果我错过了什么请告诉我。谢谢!

© www.soinside.com 2019 - 2024. All rights reserved.