1

Using node, restify and bluebird promises and a sleep-deprived mind:

let chain = Promise.try(() => {

    return AsyncCall(auth_token).then(result => {
        if (!result)
            throw new Error('AUTH_TOKEN_ERROR');
        } else {
            return facebook_data;
        }

    });

}).catch((error) => {

    res.code(401).error(error.message);
    next();

});

chain.then((result) => {
    // Gets called even though we throw the error.
});

My problem is that I really like the chain.then()-method of "ending" the promise chain (for readability), but it gets called even though .catch gets an error. I realize I can set the final .then() into the first chain block, but I want to understand this.

How can I keep the same code structure, but having a .catch()-event end the promise execution flow?

Mattis
  • 5,026
  • 3
  • 34
  • 51
  • You can have another catch... `chain.then().catch()` – elclanrs Mar 10 '16 at 22:03
  • @elclanrs Gosh darnit, you are right about that. Moving the .catch() to after the stand-alone .then() worked well. Feel free to type up an answer, if someone else haven't already. – Mattis Mar 10 '16 at 22:09
  • 1
    @Mattis you've done the right thing, although that's not quite what elclanrs was suggesting (but what he said wouldn't work anyway, since your existing `chain` will always be resolved (the output of a `.catch` call is a resolve promise, unless that call throws an exception) – Alnitak Mar 10 '16 at 22:14

1 Answers1

1

catch assumes you're handling the error. If you're not and want it to be handled at a later catch, rethrow it like this:

.catch((error) => {
    res.code(401).error(error.message);
    next();
    throw error;
});
SimpleJ
  • 13,812
  • 13
  • 53
  • 93
  • I was composing an answer exactly like this, but I hesitated because I don't think it makes any sense to `throw` here after calling the previous two lines - it happens "too late". – Alnitak Mar 10 '16 at 22:12
  • Or optionally he could `return Promise.reject(error)` instead of throwing. – idbehold Mar 10 '16 at 22:23
  • @Alnitak I'm not sure why Mattis would structure his promise this way (as opposed to how elclanrs mentioned in his comment above). I think my answer is technically correct, but I doubt it's what Mattis actually wants in his program. – SimpleJ Mar 10 '16 at 22:32