How is PromiseRejectionEvent triggered?

后端 未结 2 382
北恋
北恋 2021-01-19 01:02

I am confused about the following problem:

defined onunhandledrejection

window.onunhandledrejection = event =>{
  event.preventDefaul         


        
相关标签:
2条回答
  • 2021-01-19 01:38

    Since test2 is an async function, its result is wrapped in a Promise.

    JavaScript Async Return Value

    0 讨论(0)
  • 2021-01-19 01:41

    test2 being marked async does wrap your return value in a new promise:

    function test2() { // de-async-ified
        return new Promise(resolve => {
            const rejectedP = Promise.reject('-');
            rejectedP.finally();
            resolve(rejectedP);
        });
    }
    

    If we do compare the calls

    const result1 = test1();
    const result2 = test2();
    

    by expanding them to

    const rejectedP = Promise.reject('-');
    const finallyP = rejectedP.finally();
    const result1 = rejectedP;
    
    const result2 = new Promise(resolve => {
        const rejectedP = Promise.reject('-');
        const finallyP = rejectedP.finally();
        resolve(rejectedP);
    });
    

    we can see that the first snippet creates two promises (result1 and rejectedP being the same) while the second snippet creates three promises. All of these promises are rejected, but the rejectedP rejection is handled by the callbacks attached to it, both through ….finally() and resolve(…) (which internally does ….then(resolve, reject)).

    finallyP is the promise whose rejection is not handled in the both examples. In the second example, result2 is a promise distinct from rejectedP that is also not handled, causing the second event.

    0 讨论(0)
提交回复
热议问题