Consider example1:
var prom1 = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Prom 1 executed");
reject("Rejected");
}, 2000);
});
console.log("Before Prom 1");
window.addEventListener("rejectionhandled", function(event) {
console.log("Handled Rejection"); //never triggers
});
window.addEventListener("unhandledrejection", function(e) {
console.log("unhandledrejection");
prom1.then(null, function(err) {
console.log("Caught error");
});
});
In this scenario rejectionhandled
does not trigger. Now consider example2:
var prom1 = new Promise(function(resolve, reject) {
setTimeout(function() {
console.log("Prom 1 executed");
reject("Rejected");
}, 2000);
});
console.log("Before Prom 1");
window.addEventListener("rejectionhandled", function(event) {
console.log("Handled Rejection"); //never triggers
});
window.addEventListener("unhandledrejection", function(e) {
console.log("unhandledrejection");
setTimeout(function() {
prom1.then(null, function(err) {
console.log("Caught error");
});
}, 0);
});
Now in this instance rejectionhandled
did run. I know it has something to do with microtask/macrotask/event-loop. I know there are similar questions on SO, but I can’t seem to apply that explanation here. Probably the explanation here https://stackoverflow.com/a/57261820/3429430 should mean that whenever the promise is caught within unhandledrejection’s handler it is not considered as attached after unhandledrejection’s handler’s execution.