-1

I have a question about this Promise code. Why "Foo" is logged? I am confused since 'then' is following 'catch', and 'catch' is never called, why execution flows into 'then'?

let myPromise = new Promise((resolve, reject) => {
  resolve("Foo");
});

myPromise.catch((value) => {
  console.log('inside catch');
}).then((value) => {
  console.log(value);
});
mplungjan
  • 169,008
  • 28
  • 173
  • 236
Chen Chen
  • 13
  • 5
  • catch() will only execute when promise reject() something. – thatcoder Sep 20 '18 at 05:52
  • Try `throw("Baz");` to see the catch – mplungjan Sep 20 '18 at 05:54
  • The catch() method returns a Promise and deals with rejected cases only. – Dulanga Heshan Sep 20 '18 at 06:12
  • Maybe I get it wrong, but I feel your confusion came from the fact you might have thought `then` would only get called if `catch`'s callback was called itself. It doesn't. `then` and `catch` are both called synchronously. Each of these methods returning a new Promise. Their callbacks are called asynchronously and their execution will depend on what did happen in the Promise chain. – Kaiido Sep 20 '18 at 06:14
  • @Kaiido Thanks! Your explanation helps a lot! – Chen Chen Sep 20 '18 at 16:35

1 Answers1

0

Please read the documentation of Promise.

And catch will only be called if the promise is rejected.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise

As a side note, and not related to the question:

In most written code then usually comes before catch, although it doesn't have to be.

Domenik Reitzner
  • 1,583
  • 1
  • 12
  • 21
  • I'm sorry I'm a bit lazy, but could you point out where in these docs it's said that "*`then` should always come before `catch`*"? A simple word search against *always* only returned the paragraph about Promise#length and I can see various cases where you would want catch before then. – Kaiido Sep 20 '18 at 06:04
  • I am not the author of this question. And no it should not be a standard because both have applications. The semantic has nothing to do in here, it's just plain logic. If the logic is that you are expecting the Promise will reject and want to handle it in a way it won't break the rest of the chain, it's perfectly correct to add a catch(handlePossibleError) before the next then() – Kaiido Sep 20 '18 at 06:28
  • Yes you are right, I rewrote my answer to focus more on the real question that was asked. ;) – Domenik Reitzner Sep 20 '18 at 06:35