0
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?

hui
  • 591
  • 7
  • 22
  • You [should never use `try`/`catch` inside a promise callback](http://stackoverflow.com/a/42650428/1048572) – Bergi Mar 16 '17 at 05:02

2 Answers2

2
  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.
0

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'); });
JLRishe
  • 99,490
  • 19
  • 131
  • 169