Skip to content

Instantly share code, notes, and snippets.

@menacestudio
Last active December 14, 2015 19:38
Show Gist options
  • Save menacestudio/5137516 to your computer and use it in GitHub Desktop.
Save menacestudio/5137516 to your computer and use it in GitHub Desktop.
Using jQuery's deferred object.
/**
Author: Dennis Rongo
Description: This demonstrates the jQuery deferred object and used when running asynchronous operations (non-AJAX) functions.
Each function returns a 'promise' object that notifies the subscriber when the operation has completed.
*/
$(function(){
/** Create a long operation */
var loadQueue = function() {
var dfrQueue = new $.Deferred();
var i = 0;
var loop = window.setInterval(function() {
++i;
console.log('queue 1 - running: '+i);
if (i >= 10) {
// pass optional param to success callback
dfrQueue.resolve('queue 1');
clearInterval(loop);
}
}, 1000);
console.log('initialize test for queue 1');
return dfrQueue.promise();
};
/** Create a second long operation */
var loadQueue2 = function() {
var dfrQueue = new $.Deferred();
var i = 0;
var loop = window.setInterval(function() {
++i;
console.log('queue 2 - running: '+i);
if (i >= 5) {
// pass optional param to success callback
dfrQueue.resolve('queue 2');
clearInterval(loop);
}
}, 1000);
console.log('initialize test for queue 2');
return dfrQueue.promise();
};
/** Using $.when() for 2 asynchronous or long running operations but additional functions can be added as long as they all return a promise object. */
$.when(
loadQueue(), loadQueue2())
.then(function(arg) {
// all operations has completed and console out the argument provided by the last operation that completed.
console.log('all process succeeded: ' + arg);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment