3 ms·
Promises don't swallow errors, they pass it up to whatever next promise gets chained or any .catch() handlers registered. Browsers have an event to listen to fo
by WorldMaker 7y ago
Promises don't swallow errors, they pass it up to whatever next promise gets chained or any .catch() handlers registered. Browsers have an event to listen to for unhandled promise rejections at the global level for all those places you fired off a promise but forgot to do anything with it. (All the major browsers now show error messages and stack traces in the dev console as a default action for all unhandled promise rejections. They don't stop page execution as browsers decided against that back in the early IE/Netscape era to be more graceful in a complex event-based world. Node also spits out unhandled promise rejections to the console and hard quits a process now.)
But the juicy benefit to Promises is the (monad-based) transformation to async/await notation. Async/await notation gives you back the try { } catch { } synchronous-looking error catching that you are wishing for, all it takes is a couple new magic keywords and your code looks very similar to what it would in a magic synchronous world without promises. (Most current browsers and current versions of Node even directly support async/await today [0] directly out of the box, no need for a compiler/transpiler tool to do the transformation for you.)
[0] https://caniuse.com/#feat=async-functions https://caniuse.com/#feat=async-functions
- z3t4 7y agoEvery error that happens after the promise have completed are treated as if they where exceptions to the Promise, even though they have nothing to do with what was promised, including type, syntax, and state errors.
- z3t4 7y agoIn JavaScript there are two types of errors: First class errors that you can return, pass around and bubble up. And then there are exceptions that means the program did something unexpecting. Promises make no exception and does not treat them as first class citizens.
- WorldMaker 7y agoPromises make future exceptions. If you aren't paying attention "in the future" to catch those exceptions, they bubble to an error handler (window.onUnhandledRejection [0]), so it acts as both types of JS errors, depending on how you want to pay attention to it. async/await syntax lets you catch promise rejection exactly like you would any other type of JS exception with a try {} catch {}. [0] https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event https://developer.mozilla.org/en-US/docs/Web/API/Window/unha...
- WorldMaker 7y agoTo bring things back on topic: async/await syntax in JS inherits its magic almost directly from Haskell's do-notation and is exactly an example of why exploring Monads has been practically useful for languages far outside of the "academic ivory tower walls" of Haskell.