0

I am seeking an understanding of the below code - specifically what happens when the following code of returning string from inside catch block is encountered i.e. return 'Promise Error caught'.

function job(state) {
  return new Promise(function(resolve, reject) {
    if (state) {
      resolve('Promise success');
    } else {
      reject('Promise error');
    }
  });
}
let promise = job(true);
promise.then(function(data) {
  console.log(data);
  return job(false);
}).catch(function(error) {
  console.log(error);
  return 'Promise Error caught';
}).then(function(data) {
  console.log(data);
  return job(true);
}).catch(function(error) {
  console.log(error);
});
halfer
  • 19,824
  • 17
  • 99
  • 186
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 1
    you continue the promise chain by returning `return job(false)` but this promise rejects witch leads to the catch block – bill.gates Dec 04 '20 at 07:10
  • `.then()` and `.catch()` callbacks can either return a value (down the promise chain's success path to the next `.then()`) or throw (down the error path to the next `.catch()`). They can also return a Promise, in which case the path is determined how that Promise settles (success or error). – Roamer-1888 Dec 04 '20 at 09:51
  • @Roamer-1888 - So in this case, the catch block returns a string (instead of a promise) return 'Promise Error caught';.....So wanted to understand how that works... – copenndthagen Dec 04 '20 at 12:10
  • So the value returned by the catch callback is of type `String`. Progress down the chain will take the success path and `"Promise error caught"` will appear in the next `.then()` callback as `data`. – Roamer-1888 Dec 05 '20 at 10:30
  • Thanks...So returning a string from inside a then/catch block would cause a "success" path to be taken (instead of a "error" path which I assume is only taken for a rejected promise) ....Would that be correct understanding ? – copenndthagen Dec 05 '20 at 13:53
  • 1
    Nearly correct. Two things within a .then()/catch() callback will cause the error path to be taken; (1) a synchronous throw or (2) returning a Promise that (eventually) settles on its error path. Don't make the mistake of thinking that returning an Error object will have the same effect. It doesn't. Instead, the returned Error would be sent down the success path (which is very rarely a good thing to do). – Roamer-1888 Dec 05 '20 at 19:32
  • Not sure what your general understanding of promises is, but maybe https://stackoverflow.com/questions/16371129/chained-promises-not-passing-on-rejection answers your question? – Bergi Dec 10 '20 at 13:17

0 Answers0