Open ForbesLindesay opened 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.
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;
}
@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.
We could have a
promise(fn)
method which returns a promise, and calls the function with the resolver for that promise.Advantages
.constructor
property of a promise (see #5)Disadvantages
function
keywordSummary
I'm very much in favour of this proposal