Created
October 24, 2014 10:27
-
-
Save luque/f1fa2541c12713da234c to your computer and use it in GitHub Desktop.
Chaining a variable number of asynchronous tasks with JQuery promises (http://jsfiddle.net/qopu5vLL/)
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
$(function() { | |
function doChainedTasks(tasks) { | |
var promise = tasks[0](); | |
var results = []; | |
$.each(tasks.slice(1), function(i, task) { | |
promise = promise.then(function(value) { | |
results.push(value); | |
return task(); | |
}); | |
}); | |
promise.then(function(value) { | |
results.push(value); | |
println("All Results -> " + results); | |
}); | |
} | |
function a() { | |
var dfr = $.Deferred(); | |
setTimeout(function() { | |
println("Function a() finished"); | |
dfr.resolve("Result a"); | |
}, 500); | |
return dfr.promise(); | |
} | |
function b() { | |
var dfr = $.Deferred(); | |
setTimeout(function() { | |
println("Function b() finished"); | |
dfr.resolve("Result b"); | |
}, 1500); | |
return dfr.promise(); | |
} | |
function c() { | |
var dfr = $.Deferred(); | |
setTimeout(function() { | |
println("Function c() finished"); | |
dfr.resolve("Result c"); | |
}, 2000); | |
return dfr.promise(); | |
} | |
function println(msg) { | |
$("body).append(msg + "<br/>"); | |
} | |
var tasks = [a, b, c] | |
doChainedTasks(tasks); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment