Jan
04

Starting a promise chain to handle exceptions correctly

posted on 04 January 2017 in programming with 0 Comments

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:

  1. Ensure that doSomething always returns a promise, e.g. wrap the whole thing in a new 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.
  2. 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);
    
  3. 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);