hui
hui

Reputation: 601

difference between “Promise reject” with “try-catch”

var promise = new Promise(function(resolve, reject) {
  try {
    throw new Error('test');
  } catch(e) {
    reject(e);
  }
});
promise.catch(function(error) {
  console.log(error);
});

we can use "try-catch" to throw error

// mothod 2
var promise = new Promise(function(resolve, reject) {
  reject(new Error('test'));
});
promise.catch(function(error) {
  console.log(error);
});

we also can use "reject" to throw error.

what's difference between them?

Upvotes: 0

Views: 1532

Answers (2)

Bethleharaja G
Bethleharaja G

Reputation: 54

  1. Exceptions thrown from asynchronous functions cannot be handled with try-catch block.
  2. Promises are chain-able; prevents us from nesting code that affects readability.

Upvotes: 2

JLRishe
JLRishe

Reputation: 101662

There is no effective difference. In both cases, you're calling reject() with an error.

The following are also equivalent to what you have there:

var promise = new Promise(function(resolve, reject) {
  throw new Error('test');
});


var promise = Promise.reject(new Error('test'));


var promise = Promise.resolve().then(function () { throw new Error('test'); });

Upvotes: 0

Related Questions