garyx garyx - 1 month ago 5
AngularJS Question

Is there a difference between promise.then.then vs promise.then; promise.then

I want to know is there a difference between following two?


  1. aPromiseObj.then(fn1).then(fn2).catch(fn3);

  2. aPromiseObj.then(fn1); aPromiseObj.then(fn2); aPromiseObj.catch(fn3);



Will the work flow changed?

ps: I am in angular environment, though I would like to think this in a broader term.

Answer

You have asked about "chaining" vs. "branching".

Assuming that f1 and f2 represent asynchronous operations that return promises, yes there is a significant difference. For option 1:

  1. It serializes fn1 and fn2 so that fn2 is not called until after the promise returned by fn1 has been resolved.
  2. .catch() applies to an error in either fn1 or fn2
  3. fn2 will not be called if fn1 rejects.

For option 2:

  1. fn2 does not wait for fn1 to resolve. fn2 is called as soon as fn1 returns similar to fn1(); fn2();.
  2. The .catch() does not apply to either because it is not on the promise that is created by either of the .then() calls.
  3. Both fn1 and fn2 will be called regardless of an error in either.

Another related question/answer: Understanding javascript promises; stacks and chaining