Jan
04
Starting a promise chain to handle exceptions correctly
Warning: Please consider that this post is over 7 years old and the content may no longer be relevant.
Here’s a little promises quirk that I’ve overlooked for a while. Generally we all write promises like this:
doSomething()
.then(doSomethingElse)
.then(doSomethingFurther)
.catch(handleError);
And we know that any exception raised will skip to the catch handler. Except for the initial doSomething()
call. If an exception is raised here it will be treated like a normal exception and stop executing all the rest of your code. So how do you deal with it? You could:
- Ensure that
doSomething
always returns a promise, e.g. wrap the whole thing in anew Promise(function (resolve, reject) { .. })
. While this isn’t a bad practice it requires the calling code to assume the function has been implemented correctly, not something I’d rely on. - Wrap the start of the promise chain in a promise like this:
new Promise(function (resolve, reject) { resolve(doSomething()); }) .then(doSomethingElse) .then(doSomethingFurther) .catch(handleError);
- Start the promise chain with a dummy promise like this (my preferred approach):
Promise.resolve() .then(doSomething) .then(doSomethingElse) .then(doSomethingFurther) .catch(handleError);
or in angular:
$q.when() .then(doSomething) .then(doSomethingElse) .then(doSomethingFurther) .catch(handleError);