Created
October 21, 2011 13:33
-
-
Save donabrams/1303860 to your computer and use it in GitHub Desktop.
$.Deferred Pipeline
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
define(["jquery"], function($) { | |
// | |
// Given a list of functions that return a promise or an object, | |
// Set them up to execute them in order using those promises. | |
// and returns a promise that resolves after the last promises returned by the function pipeline resolves. | |
// | |
var deferredPipeline = $.deferredPipeline = function(/* [function, ]*/) { | |
//reversed pipeline | |
var toPipe = Array.prototype.slice.call(arguments).reverse(); | |
if (toPipe.length == 0) { | |
return $.when(); | |
} else if (toPipe.length == 1) { | |
return toPipe[i](); | |
} | |
var dfd = $.Deferred(); | |
var lastFunc = function() { | |
toPipe[0](arguments).then( | |
function(){dfd.resolve(arguments);}, | |
function(){dfd.reject(arguments);}); | |
}; | |
for (var i = 1;i<toPipe.length;i++) { | |
var toResolveNext = lastFunc; | |
lastFunc = function() { | |
$.when(toPipe[i](arguments)).then(toResolveNext); | |
}; | |
} | |
return dfd.promise(); | |
}; | |
return deferredPipeline; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment