Skip to content

Instantly share code, notes, and snippets.

@donabrams
Created October 21, 2011 13:33
Show Gist options
  • Save donabrams/1303860 to your computer and use it in GitHub Desktop.
Save donabrams/1303860 to your computer and use it in GitHub Desktop.
$.Deferred Pipeline
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