Try/Catch always needed for await?

Alan Johnson alan at breakrs.com
Fri Oct 14 15:25:27 UTC 2016


To perhaps clarify this point a bit, it is very important to `.catch()` and react appropriately at the ends of promise chains. If synchronous code fails for an unexpected reason, a visible crash will definitely happen. This is not the case for promises, because there’s no way for the runtime to know whether that promise is just some middle step in the chain, in which case you’d want to propagate rejection, rather than throw a synchronous exception. Having unexpected errors be silently swallowed is definitely a problematic property of promises, which you have to guard against.

It probably would be possible for the runtime to report crashes of promises that have no registered `.then()`. The only problem is, it’s totally possible the programmer is going to attach a `.then()` or `.catch()` later on to a promise that has already failed. Some promise libraries offer a `.done()` that has the semantics of “crash if this promise rejects”. But arguably, this should be the normal behavior, with an opt-out instead, so that it is assumed that you want rejected promises without any `.then()`s to throw synchronous exceptions. Something like a `.noFail()` could opt out

> On Oct 14, 2016, at 09:30, Bergi <a.d.bergi at web.de> wrote:
> 
> Jordan Rome schrieb:
>> My apologies if this has already been discussed but what is the "preferred"
>> pattern for using await ? Since await, which runs on promises, will now
>> throw if the promise is rejected (preventing execution of code after the
>> await and killing the process in Node), is it neccesary to always be
>> wrapping await in try/catch?
> 
> No. Just like in synchronous code, you only wrap a part of your code in try-catch if you actually want to *handle* an exception.
> 
> If you don't handle it, it will bubble as usual and reject the promise returned by the `async function`. Let the caller deal with the exceptions you can't handle - just like always.
> Of course, in the top-level invocation it might be a good idea to use a `catch` (or the `.catch()` method) to catch any exceptions and log them to whereever you want if you don't want to get an unhandled rejection, but those are usually exceptions you *don't expect* so you might not need to deal with them at all.
> 
> - Bergi
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20161014/017a7ab1/attachment.html>


More information about the es-discuss mailing list