Skip to content

Instantly share code, notes, and snippets.

@heymatthew
Created August 20, 2012 21:07
Show Gist options
  • Save heymatthew/3407907 to your computer and use it in GitHub Desktop.
Save heymatthew/3407907 to your computer and use it in GitHub Desktop.
Chaining Promises with JQuery in Javascript
// Prereq: underscore.js and jquery loaded
var p1 = $.Deferred();
var p2 = $.Deferred();
// We want something that chains promises, so something like...
//p1.done(
// function addNext() {
// p2.done(
// function addNext() {
// console.log('oh hai');
// }
// )
// }
//);
function chainPromise( promiseList, successCallback, failCallback ) {
var hasFailed = false;
// When all promises resolve, call successCallback();
var resolver = _.reduce(
promiseList,
function iterator(memo, promise) {
return function addNext() {
if ( !hasFailed ) {
promise.done(memo);
}
};
},
successCallback
);
resolver();
// If any promise fails, call failCallback, and only call it once();
_.each(
promiseList,
function iterator(promise) {
promise.fail(
function onFail() {
if ( !hasFailed ) {
hasFailed = true;
failCallback();
}
}
)
}
);
}
chainPromise( [p1, p2],
function() { console.log('oh hai'); },
function() { console.log('oh noes'); }
);
console.log('loaded with promises');
p1.resolve();
console.log('almost there');
p2.resolve();
//console.log('rejected...');
//p2.reject();
//p1.reject();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment