0

rejectionhandled事件应在unhandledrejection事件处理程序将拒绝处理程序 ( catch()) 附加到 Promise 后触发,但它没有

在 node.js 中,我们有相同的unhandledRejectionrejectionHandled可以正常工作的事件

我错过了什么?

onunhandledrejection = function(ev){                       // event property triggered as expected (promise ha a missing rejection handler)
    console.log( 'promise has no rejection handler!' );
    ev.promise                                             // the promise that has no rejection handler 
        .catch(err => console.log(err))                    // attaching the rejection handler to the promise  (THIS SHOULD TRIGGER THE rejectionhandler event)
}

onrejectionhandled = function(ev){                         // NOT triggered 
    console.log( 'rejection handled!' );
}

addEventListener('rejectionhandled', function(ev){         // NOT triggered 
    console.log( 'rejection handled!' );
})


Promise.reject("I'm rejected!");                           // rejected promise without rejection handler 

4

1 回答 1

1

通过这个答案和其中提到的规范内容,似乎如果拒绝没有在当前事件循环中被捕获,而是在任何以后的事件循环中被捕获,那么在那个事件循环中,rejectionhandled将被触发。

window.addEventListener("rejectionhandled", (ev) => {
    console.log("rejectionhandled ev.promise:", ev.promise);
    console.log("rejectionhandled ev.reason:", ev.reason);
});

let p = Promise.reject("oops");

// setTimeout callback will be called in next event loop
setTimeout(() => {
    p.catch((err) => {console.log("handle rejection: " + err)});
});

// output:
// handle rejection: oops
// rejectionhandled ev.promise: Promise {<rejected>: 'oops'}
// rejectionhandled ev.reason: oops
于 2021-12-12T18:28:02.587 回答