Search code examples
javascriptes6-promise

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);
});

Solution

  • 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.