-1

I have the following chained functions that all implement promises utilizing Q:

validateToken(context).then(parseFormData, get403).then(createReport, get400).then(send200, get400).catch(get500);

e.g. All of them have somewhere within them:

let deferred = q.defer();
..
deferred.resolve(true);
deferred.reject(false);
return deferred.promise;

The first function validateToken calls a deferred.reject. This then results with get403 being called, as expected; but createReport, get400 and get500 are also being called? This confuses me. I thought only the first error handler was hit in the chain?

Can someone please explain what is happening, and if there is a way for me to get the desired behavior where only the most immediate reject/error handler is called?

Doug
  • 6,446
  • 9
  • 74
  • 107

1 Answers1

1

That depends on what on403 returns. If nothing, it is assumed to be a resolve - which explains the behavior you are seeing. Remember, onReject is equivalent to a catch, which, as a concept, allows you to continue processing as if an error didn't happen

If you want to continue down the reject chain then you have to return Promise.reject(). Otherwise you have to rethink your promise chaining.

Leroy Stav
  • 722
  • 4
  • 12
  • Interesting, so if my reject handler doesn't return a reject as well it will continue down the chain? I didn't realize that. I'll have to play around with this. – Doug Jan 23 '19 at 17:28
  • Thank-you. This definitely worked. I don't know how I got the wrong understanding of how the chaining works; but this is a very simple explanation. If you know of any resources that talk about this in more detail that would probably make this answer even better, but it works for me! Thanks again! – Doug Jan 23 '19 at 17:42
  • 1
    Honestly there are a million resources online that talk about how Promise chaining works, and specifically the MDN documentation (pretty much the *de facto* documentation for all things javascript related) covers it well https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise – Leroy Stav Jan 23 '19 at 19:12