JS. Reject vs throw and catch vs rejectHandler

Both, reject and throw can be handled with catch

reject inside promise will be handled by 2-d argument of then, and if it is not used – by catch after

const promise = new Promise((resolve, reject) => {
  reject('rejected');
})

promise.then(result => console.log(result), error => console.log(error)).catch(e => console.log(e));

throw will be handled only in catch

const promise = new Promise((resolve, reject) => {
  throw new Error('rejected');
})

promise.then(result => console.log(result), error => console.log(error)).catch(e => console.log(e));

What approach is better ? Lets look at this example…

somePromise().then(function () {
    throw new Error('oh noes');
  })
  .catch(function (err) {
   // will be handled here
  });

somePromise().then(function () {
  throw new Error('oh noes');
}, function (err) {

  // will not be handled here
});

so looks likes catch is better…

Now lets look at this code

new Promise(function() {
  setTimeout(function() {
    throw 'or nah';
    // return Promise.reject('or nah'); also won't work
  }, 1000);
}).catch(function(e) {
  console.log(e); // doesn't happen
});

in this particular case it is ok, if to use reject

new Promise(function(resolve, reject) {
  setTimeout(function() {
    reject('or nah');
  }, 1000);
}).catch(function(e) {
  console.log(e); // works!
});
This entry was posted in Без рубрики. Bookmark the permalink.