promises-aplus / constructor-spec

Discussion and drafts of a possible spec for creating and resolving promises
10 stars 4 forks source link

Use the `promise(fn)` notation #3

Open ForbesLindesay opened 11 years ago

ForbesLindesay commented 11 years ago

We could have a promise(fn) method which returns a promise, and calls the function with the resolver for that promise.

Advantages

I'm very much in favour of this proposal

domenic commented 11 years ago

Given what I discovered in #5, I think this approach should definitely exist. Whether we do deferreds also is a different question, but I'm coming around to a promise constructor idea using this pattern.

ForbesLindesay commented 11 years ago

I think if we do go with this as our primary promise creation method, we need to strictly enforce that fn is called in the same turn of the event loop. That way it would be possible to do something like:

function Deferred() {
  if (!(this instanceof Deferred)) return new Deferred();
  var resolver;
  var promise = new Promise(function (res) { resolver = res; });
  this.resolver = resolver;
  this.promise = promise;
}
lsmith commented 11 years ago

@ForbesLindesay Good point about fn being called in the same turn of the event loop. In a Deferred + Promise implementation, the creation of the pair is synchronous, and the setup code to resolve the promise would (or at least could and usually would) then occur directly afterward. For parity with this expectation, it would be worth it to specify that the executor function, as I've taken to calling it, is executed synchronously.