0

Basically I want to run the same code regardless if the code throws an error or not. Now I'm doing this:

.then((resp) => {
    assert(false);
}, err => {
    assert.equal(2, err.error.errors.length);
    });
});

But I would like to do something like this:

.something((resp, err) => {
    assert.equal(400, resp.statusCode)
    assert.equal(2, err.error.errors.length);
}
Andreas
  • 21,535
  • 7
  • 47
  • 56
Himmators
  • 14,278
  • 36
  • 132
  • 223
  • Some promise libraries like bluebird implement a `.finally()` – slebetman Jul 19 '16 at 05:49
  • @slebetman, cool, but it doesn't seem to have any variables? – Himmators Jul 19 '16 at 05:52
  • 1
    Your `something` callback doesn't make sense. There's no way `resp` and `err` would ever be available at the same time - there's a good reason why `then` takes *two* callbacks. – Bergi Jul 19 '16 at 05:55
  • possible duplicate of [ES6 promise settled callback](http://stackoverflow.com/q/32362057/1048572)? – Bergi Jul 19 '16 at 05:58

1 Answers1

3

You can do it...

...just use catch and return something from it, then use then on the promise .catch returns:

thePromise
    .catch(err => err)
    .then(resultOrError => {
        // Your code
    });

The argument your then callback receives (resultOrError in the above) will be the resolved value if the promise was resolved, or the rejected value (loosely, "error") if it was rejected. You can naturally do something more in catch if you want to differentiate them.

Example (run it a few times, you'll see it get resolved, and also rejected):

let p = new Promise((resolve, reject) => {
  setTimeout(() => {
    if (Math.random() < 0.5) {
      resolve("success");
    } else {
      reject("error");
    }
  }, 0);
});
p.catch(err => err).then(resultOrError => {
  console.log("Got this:", resultOrError);
});

...but alternately

...you can just have a a common function both callbacks call, after using the resolved value or the rejected value:

function doSomethingNoMatterWhat() {
    // ...
}

thePromise
    .then(result => {
        // Presumably use `result`, then:
        doSomethingNoMatterWhat();
    })
    .catch(error => {
        // Presumably use `error`, then:
        doSomethingNoMatterWhat();
    });
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875