简体   繁体   中英

ES6 Promises Error Handling

I'm currently reading "YKDJS - Async & Performance" by Kyle Simpson, in particular Chapter 3 - Promises.

The author says that any Promise for which no rejection handler is registered receives a default one:

let p = new Promise(function(resolve, reject) { resolve("Yay!"); });
p.then(
function(val) { /* Do whatever */ } 
   /* Default rejection handler
   , function(e) { throw e; } */
);

Later in the chapter he claims that one problem with the way Promise s are designed is the following:

In any Promise chain, any error that happens in one of the handler functions of the last Promise in the chain is just "swallowed" instead of being reported. He proposes to change the way Promise s work so that any Promise that doesn't have a rejection handler reports the error by throwing a global error. Then he proposes a theoretical Promise#defer() function one could use on a Promise to prevent this reporting behavior.

Now my question is: How do these two go together? It's true that any Promise that doesn't have a rejection handler receives a default one which just throws the rejection value as a global error:

Promise.reject("Oops");
/* VM668:1 Uncaught (in promise) Oops */

So already Promise s seem to work in just the way he proposes. Am I misunderstanding something? Thanks for any help.

The Uncaught Handling he mentions in

Some Promise libraries have added methods for registering something like a "global unhandled rejection" handler, which would be called instead of a globally thrown error. But their solution for how to identify an error as "uncaught" is to have an arbitrary-length timer, say 3 seconds, running from time of rejection. If a Promise is rejected but no error handler is registered before the timer fires, then it's assumed that you won't ever be registering a handler, so it's "uncaught."

In practice, this has worked well for many libraries, as most usage patterns don't typically call for significant delay between Promise rejection and observation of that rejection.

has been standardised as unhandled rejection warnings (not using an arbitrary timer, but firing right away). It does indeed work quite well.

He also states in Chapter 4 of ES6 & Beyond

[When] we are not listening for that rejection, […] it will be silently held onto for future observation. If you never observe it by calling a then(..) or catch(..) , then it will go unhandled. Some browser developer consoles may detect these unhandled rejections and report them, but this is not reliably guaranteed; you should always observe promise rejections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM