Talespin_Kit
Talespin_Kit

Reputation: 21877

Is it valid to resolve promise in the promise constructor?

Is it valid to resolve the promise in the constructor like this

var promise1 = new Promise(function(resolve, reject) {
    resolve('foo');
});

instead of the resolving after the construction creation like the following

var promise1 = new Promise(function(resolve, reject) {
  setTimeout(function() {
    resolve('foo');
  }, 300);
});

Upvotes: 0

Views: 77

Answers (1)

traktor
traktor

Reputation: 19301

Yes, it is perfectly acceptable to resolve a new Promise synchronously in the constructor. IIRC, it is even a test case in the A+ promise validation suite.

However if the resolution is not conditional, it is more clearly achieved using the ES6 Promise static method `resolve':

var promise1 = Promise.resolve( 'foo');

Note the two approaches differ if errors are thrown:

  • If the executor throws an error, new Promise( executor) returns a rejected promise.
  • If evaluation of the argument for Promise.resolve throws an error, the exception prevents a call to Promise.resolve taking place.

Upvotes: 2

Related Questions