Error handling
As we saw earlier, then
takes two arguments, one for success, one for failure (or fulfill and reject, in promises-speak):
.fail, .catch
Some librairies implement the method .fail
(or .catch
) which is equivalent to .then(undefined, func)
, for example:
Rejection order
The following codes are not equivalent:
and
The difference is subtle, but extremely useful. Promise rejections skip forward to the next then
with a rejection callback (or fail
, since it's equivalent). With then(func1, func2)
, func1
or func2
will be called, never both. But with then(func1).fail(func2)
, both will be called if func1
rejects, as they're separate steps in the chain.
Javascript Exceptions
Rejections happen when a promise is explicitly rejected, but also implicitly if an error is thrown in the constructor callback. Let's take a look at the previous example:
The Javascript method JSON.parse can throw an exception (SyntaxError
) if the string is not valid JSON. This exception (if occurs) will be handled by the .fail
.
Basically, the .then(func)
is encapsulating the call to func
with a try { func(resolved) } catch (e) { // return rejected promise }
.
Last updated
Was this helpful?