Ok, answering to myself. I misunderstood how unhandledrejection
event actually works.
I'm coming from .NET where a failed Task
object can remain unobserved until it gets garbage-collected. Only then UnobservedTaskException
will be fired, if the task is still unobserved.
Things are different for JavaScript promises. A rejected Promise
that does not have a rejection handler already attached (via then
, catch
, await
or Promise.all/race/allSettle/any
), needs one as early as possible, otherwise unhandledrejection
event may be fired.
When unhandledrejection
will be fired exactly, if ever? This seems to be really implementation-specific. The W3C specs on "Unhandled promise rejections" do not strictly specify when the user agent is to notify about rejected promises.
To stay safe, I'd attach the handler synchronously, before the current function relinquishes the execution control to the caller (by something like return
, throw
, await
, yield
).
For example, the following doesn't fire unhandledrejection
, because the await
continuation handler is attached to p1
synchronously, right after the p1
promise gets created in already rejected state. That makes sense:
window.addEventListener("unhandledrejection", event => {
console.warn(`unhandledRejection: ${event.reason.message}`);
});
async function main() {
const p1 = Promise.reject(new Error("Rejected!"));
await p1;
}
main().catch(e => console.warn(`caught on main: ${e.message}`));
The following still does not fire unhandledrejection
, even though we attach the await
handler to p1
asynchronously. I could only speculate, this might be happening because the continuation for the resolved promised is posted as a microtask:
window.addEventListener("unhandledrejection", event => {
console.warn(`unhandledRejection: ${event.reason.message}`);
});
async function main() {
const p1 = Promise.reject(new Error("Rejected!"));
await Promise.resolve(r => queueMicrotask(r));
// or we could just do: await Promise.resolve();
await p1;
}
main().catch(e => console.warn(`caught on main: ${e.message}`));
Node.js (v14.14.0 at the time of posting this) is consistent with the browser behavior.
Now, the following does fire the unhandledrejection
event. Again, I could speculate that's because the await
continuation handler is now attached to p1
asynchronously and on some later iterations of the event loop, when the task (macrotask) queue is processed:
window.addEventListener("unhandledrejection", event => {
console.warn(`unhandledRejection: ${event.reason.message}`);
});
async function main() {
const p1 = Promise.reject(new Error("Rejected!"));
await new Promise(r => setTimeout(r, 0));
await p1;
}
main().catch(e => console.warn(`caught on main: ${e.message}`));
I personally find this whole behavior confusing. I like the .NET approach to observing Task
results better. I can think of many cases when I'd really want to keep a reference to a promise and then await
it and catch any errors on a later timeline to that of its resolution or rejection.
That said, there is an easy way to get the desired behavior for this example without causing unhandledrejection
event:
window.addEventListener("unhandledrejection", event => {
console.warn(`unhandledRejection: ${event.reason.message}`);
});
async function main() {
const p1 = Promise.reject(new Error("Rejected!"));
p1.catch(console.debug); // observe but ignore the error here
try {
await new Promise(r => setTimeout(r, 0));
}
finally {
await p1; // throw the error here
}
}
main().catch(e => console.warn(`caught on main: ${e.message}`));
finally
clause doesn't do the same thing as thecatch
clause of atry
.throw
from inside a promise that does an async task, if you replacenew Promise(r => setTimeout(r, ms))
withnew Promise(r => r())
there will be no unhandled rejections.unhandledRejection
gets fired doesn't have to do anything with whether I usecatch
orfinally
here. I've now explained the reason for it.