promises-aplus / constructor-spec

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

To `new` or not to `new` #4

Closed ForbesLindesay closed 10 years ago

ForbesLindesay commented 11 years ago

Should promise libraries work with new or should it just be a straight forward function call.

ForbesLindesay commented 11 years ago

Personally I'm not a huge fan of new and would prefer implementations to always do something like:

function Promise() {
  if(!(this instanceof Promise)) return new Promise();
}

If they do need to use new.

domenic commented 11 years ago

I am a fan of new but am fine with the omitting it, since that matches the built-ins (Date and RegExp).

I wonder if there's a way to do this, though, that doesn't fail when called on an already-existing instance. I.e. Promise.call(myPromise) will have weird behavior due to the instanceof line above.

ForbesLindesay commented 11 years ago

If you're using that to do inheritance (and you've done inheritance properly) it should just pass the instanceof check.

If you're using it as a mixin I'd tend towards explicit mixin support using either promise(obj) or promise.mixin(obj)

ForbesLindesay commented 11 years ago

Part of the reason I'm anti new here is that you're not actually constructing a promise, you're constructing a Deferred the promise is constructed internally by the promise library. I'm fine with libraries using whatever they want internally.

ForbesLindesay commented 11 years ago

Actually, if we were thinking var promise = new Promise(fn) then I prefer it somewhat. I'd still like to do the instanceof check though so that not using new is supported.

domenic commented 11 years ago

Yes, that's definitely what I was thinking. And yeah, I guess the instanceof check is the best we can do for emulating Date/RegExp/Map/Set/etc.

ForbesLindesay commented 11 years ago

I had in my head that we were talking about doing:

let {resolver, promise} = new Promise();

for some reason, which was why I was struggling to make sense of a new operator.

lsmith commented 11 years ago

+1 to optional new, though a nitpick (not worth commenting further on) is that in functional form, I would expect var p = promise(fn);, not var p = Promise(fn);. Easy enough to remedy with aliases, e.g. Promise.create = Promise; or var promise = Promise;.