How is PromiseRejectionEvent triggered?

2020-04-07 06:39发布

问题:

I am confused about the following problem:

defined onunhandledrejection

window.onunhandledrejection = event =>{
  event.preventDefault();
  console.log('catch unhandlerejection', event)
}

and two test functions

function test1() {
    const rejectedP = Promise.reject('-');
    rejectedP.finally();
    return rejectedP;
}

async function test2() {
    const rejectedP = Promise.reject('-');
    rejectedP.finally();
    return rejectedP;
}

when i called test1,only caught one onunhandledrejection,but when i called test2,i caught two.

What is the difference between test1 and test2?

回答1:

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.



回答2:

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

JavaScript Async Return Value