Skip to content

Instantly share code, notes, and snippets.

@su10
Created November 2, 2014 09:46
Show Gist options
  • Save su10/784d5c3f9ad80fd19537 to your computer and use it in GitHub Desktop.
Save su10/784d5c3f9ad80fd19537 to your computer and use it in GitHub Desktop.
promise-as3のPromise#when実装
public function when( ...args ):Promise {
if( args.length == 1 && args[0] is Array ) {
args = args[0];
}
// 引数が0個ならreject
if( args.length == 0 ) {
return this.then(
function( value:* ):void {
Deferred.reject('arguments must not be empty.');
},
function( reason:* ):void {
Deferred.reject( reason );
}
);
}
var d:Deferred = new Deferred();
this.then(
function( value:* ):void {
var results:Array = [];
var resolvedCount:uint = 0;
for( var i:int = 0, l:int = args.length; i < l; i++ ) {
var callback:Function = (function( index:uint ):Function {
return function( value:* ):void {
results[index] = value;
// すべてのコールバックの実行が完了したらresolve
if ( ++resolvedCount == args.length ) {
d.resolve(results);
d = null;
}
}
})(i);
var errback:Function = function( error:* ):void {
d.reject(error);
};
if ( Promise.isThenable(args[i]) ) {
args[i].then(callback, errback);
} else if ( args[i] is Function ) {
Promise.when(value).then(args[i]).then(callback, errback);
}
}
},
function( reason:* ):void {
d.reject( reason );
}
);
return d.promise;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment