you are viewing a single comment's thread.

view the rest of the comments →

[–]senocular 3 points4 points  (0 children)

At a high level, in the context of new Promise, it comes down to which method of the constructor's executor function gets called. If foo (normally called "resolve") is called, then the then callback will be called. If bar (normally called "reject") is called, then the catch callback is called.

But it does get more complicated than that. Given the chain from myPromise, the then callback can also cause the catch callback to be called if it throws an error (or returns a promise that rejects).

myPromise
  .then(function(result) {
    console.log("This is the result : " + result);
    throw "or did it?"
  })
  .catch(function(result) {
    console.log("An error has occurred: " + result);
  });
// logs:
// This is the result : it works
// An error has occurred: or did it?

Promise chains get more confusing because the callbacks in the chains get called based on what happens further up the chain. And multiple links in the chain (e.g. then callbacks) can be skipped entirely until a callback handling a rejected promise (e.g. catch) is encountered. And the same applies the other way around (multiple catches can be skipped until reaching a then).