Permalink
Browse files

Add promise next method

  • Loading branch information...
1 parent ca5f3e4 commit 197fbf7f8a45a10b38c84a1c9ca39f0832f6dea1 @zzdhidden committed Dec 9, 2011
Showing with 54 additions and 0 deletions.
  1. +54 −0 lib/util.js
View
@@ -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)
@@ -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.