0

seems we prefer to use catch to handle the exception since the reject function may miss some errors, e.g. in below code the error a is not defined will not be cached.

const promise = new Promise((resolve,reject) => {
  console.log(1)
  resolve('successfully')
})
promise
  .then((data) => {
    console.log(data)
    console.log(a)
  }, (err) => {
    console.log(err)
  })

we prefer to use catch method to catch the errors like below:

promise
  .then((data) => {
    console.log(data)
    console.log(a)
  }).catch(err => {
    console.log(err);
})

My question is: are there any solutions that need to use reject and catch method at the same time?

jeff
  • 3
  • 3

1 Answers1

0

They simply chain differently.

promise.then(foo, bar)

Here bar will not handle any errors which may occur in foo.

promise.then(foo).catch(bar)

Here bar will handle any errors occurring in either promise or foo.

So, yes, sometimes you want one, sometimes you want the other, sometimes you may want both.

function foo() {
  throw 'foo';
}

function bar(err) {
  console.log('Caught', err);
}

Promise.resolve().then(foo, bar);  // Uncaught error
Promise.reject('promise').then(foo, bar);
Promise.resolve().then(foo).catch(bar);
Promise.reject('promise').then(foo).catch(bar);
Promise.resolve().then(foo, bar).catch(bar);

A practical example perhaps:

someOperation()
  .then(
    result => someOtherFunction(result.value),
    err => {
      console.warn('Operation failed!', err);
      return 'alternative value';
    }
  )
  .then(result => alert('The result is: ' + result))
  .catch(err => console.error('Everything is wrong :(', err);

If someOperation succeeds, we continue processing its value, otherwise we'll substitute some default value; and if anything anywhere in the entire chain fails, we have a global final error handler.

deceze
  • 510,633
  • 85
  • 743
  • 889
  • I didn't understand the OP's question this way - I think an example showing when you'd use _both_ the onRejected parameter of `then` and `catch` would be worthwhile and maybe a synchronous example. – Benjamin Gruenbaum Jun 11 '18 at 12:14
  • @deceze Thanks a lot for your answer! does that means when it is not an error, maybe just an alternative value we may use onRejected method to handle, if it's a real error, something like not defined error, we refer to use catch to handle the error? is that correct? – jeff Jun 12 '18 at 03:13
  • @jeff It simply depends on where you expect errors to occur and how you want to handle them. – deceze Jun 12 '18 at 04:25
  • @deceze Thanks! you resolved my question, so basically, catch is just another way of onReject method which will handle the errors on the last step , if we need to handle the error in the middle steps, we can use onReject method. – jeff Jun 12 '18 at 10:49