Understanding javascript promises; stacks and chaining

You are illustrating the different between chaining and branching. Chaining wil sequence multiple async operations so one starts when the prior one finishes and you can chain an arbitrary number of items to sequence one after the other.

Branching hooks up multiple async operations to all be in flight at the same time when one trigger operation completes.

Implementations 1 and 3 are the same. They are chained. Implementation 3 just uses a temporary variable to chain, whereas implementation 1 just uses the return value from .then() directly. No difference in execution. These .then() handlers will be called in serial fashion.

Implementation 2 is different. It is branched, not chained. Because all subsequent .then() handlers are attached to the exact same serverSidePromiseChain promise, they all wait only for the first promise to be resolved and then all subsequent async operations are all in flight at the same time (not serially as in the other two options).


It may be helpful in understand this to dive one level down into how this works with promises.

When you do (scenarios 1 and 3):

p.then(...).then(...)

What happens is as follows:

  1. The interpreter takes your p variable, finds the .then() method on it and calls it.
  2. The .then() method just stores the callback it was passed and then returns a new promise object. It does not call its callback at this time. This new promise object is tied to both the original promise object and to the callback that it stored. It will not resolve until both are satisfied.
  3. Then the second .then() handler on that newly returned promise is called. Again, the .then() handler on that promise just stores the .then() callbacks and they are not yet executed.
  4. Then sometime in the future, the original promise p gets resolved by its own async operation. When it gets resolved, it then calls any resolve handlers that it stores. One of those handlers will be the callback to the first .then() handler in the above chain. If that callback runs to completion and returns either nothing or a static value (e.g. doesn’t return a promise itself), then it will resolve the promise that it created to return after .then() was first called. When that promise is resolved, it will then call the resolve handlers installed by the second .then() handler above and so on.

When you do this (scenario 2):

p.then();
p.then();

The one promise p here has stored resolve handlers from both the .then() calls. When that original promise p is resolved, it will call both of the .then() handlers. If the .then() handlers themselves contain async code and return promises, these two async operations will be in flight at the same time (parallel-like behavior), not in sequence as in scenario 1 and 3.

Leave a Comment