Reputation: 21877
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
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:
new Promise( executor)
returns a rejected promise.
Promise.resolve
throws an error, the exception prevents a call to Promise.resolve
taking place.
Upvotes: 2