Skip to content

Commit

Permalink
Add promise next method
Browse files Browse the repository at this point in the history
  • Loading branch information
arronzhang committed Dec 9, 2011
1 parent ca5f3e4 commit 197fbf7
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions lib/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ var jQuery = require("jquery-deferred")

exports.parseArgs = parseArgs;
exports.extend = extend;
exports.next = next;

function parseArgs (args) {
var all = slice.call(args, 0)
Expand Down Expand Up @@ -82,3 +83,56 @@ function extend(object, fromObject, getters, ignores, originalName, setters) {
} );
}

/**
* next
*
* run promise object step by step.
*
* next( aPromise )
* .next( function( aValue ){
* return bPromise;
* } )
* .next( function( aValue, bValue ){
* return cPromise;
* } )
* .done( function( aValue, bValue, cValue ){
* } )
* .fail( errorCallback );
*
* @param {Function} firstParam first can be a Promise object
* @return {Promise}
*
*/

function next ( firstParam ) {
if( ! jQuery.isFunction( this.promise ) ) {
//The first deferred
var promise = jQuery.isFunction( firstParam ) ? firstParam() : firstParam;
promise.next = next;
return promise;
}
var dfd = jQuery.Deferred();
this.done( function() {
var last = slice.call( arguments )
, res;
try{
res = firstParam.apply( null, last );
} catch( e ) {
res = e;
}
jQuery.isFunction( res && res.promise ) ?
res.done( function() {
var args = slice.call( arguments );
for (var i = last.length - 1; i >= 0; i--) {
args.unshift( last[i] );
}
dfd.resolve.apply( dfd, args );
} ).fail( dfd.reject )
: dfd.reject( res );

} ).fail( dfd.reject );

var promise = dfd.promise();
promise.next = next;
return promise;
}

0 comments on commit 197fbf7

Please sign in to comment.