CC-Archived / promise-as3

Promises/A+ compliant implementation in ActionScript 3.0
168 stars 55 forks source link

Behavior of Promise.when(Promise) #31

Open fwienber opened 10 years ago

fwienber commented 10 years ago

Currently, if you call Promise.when() with a promise, a new promise is returned with that promise as its resolved value. Is that the intended semantics? I would have expected the promise itself to be returned.

johnyanarella commented 10 years ago

Although I documented that method as returning a new Promise, there is room here for an optimization to return the same Promise instance if Promise.when() is supplied a trusted Promise.

I don't see any harm in making that change, and I think the utility methods would greatly benefit because many unnecessary Promise instantiations could potentially be avoided.

Are you sure about your claim that it returns a Promise that fulfills with a Promise instance as its value? It should be (and in my experience is) returning a Promise that resolves with the supplied Promise's resolved value (fulfills with its fulfillment value or rejects with its rejection reason).

var fulfilledPromise:Promise = Deferred.resolve( 'Test' );
var rejectedPromise:Promise = Deferred.reject( new Error( 'Test Message' ) );

Promise
    .when( fulfilledPromise )
    .then( function ( value:* ):* { 
        // value will be "Test" 
        // ...
    } );

Promise
    .when( rejectedPromise )
    .otherwise( function ( error:Error ):* {
        // error will be Error with 'Test Message' as its message.
        // ...
    } );

Note that there is a difference between resolving and fulfilling a Promise. I suspect you read the implementation for Promise.when() and assumed it fulfilled that Deferred instance with the Promise rather than resolving with it.

See: http://promises-aplus.github.io/promises-spec/#the_promise_resolution_procedure

fwienber commented 10 years ago

You are right, the returned promise assumes the state of the given promise. So the only question that remains is whether the promise itself should be returned instead of a new one in case the promise is "safe" (an instance of Promise). If I remember correctly, there was a reason why then does not return the same promise returned by an onFulfilled handler, but a new one assuming the state of the returned promise. There is some special case where there are "aliasing" effects. So we would have to make sure this special case is not applicable here.