Last active
December 14, 2015 15:59
-
-
Save gravesm/5112054 to your computer and use it in GitHub Desktop.
Control a queue of jQuery AJAX requests from within an XHR callback, rather than just from the return promise object. For example, only run the next request if some aspect of the data from the current request is true.
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
var Queue = function() { | |
var reqs = [], | |
dfds = []; | |
function run() { | |
var next = reqs.shift(); | |
if (next) { | |
$.ajax(next); | |
} | |
} | |
this.add = function(reqObj, cleanup) { | |
var dfd = $.Deferred(); | |
if (cleanup) { | |
dfd.fail(cleanup); | |
} | |
dfd.then( | |
function() { | |
dfds.shift(); | |
if (reqs.length) { | |
run(); | |
} | |
}, | |
function(propagate) { | |
dfds.shift(); | |
if (propagate && dfds.length) { | |
dfds[0].reject(true); | |
} | |
} | |
); | |
reqObj.context = { | |
dfd: dfd | |
} | |
reqs.push(reqObj); | |
dfds.push(dfd); | |
return this; | |
} | |
this.run = function() { | |
run() | |
} | |
} | |
/*** Example usage ***/ | |
var q = new Queue(); | |
q.add({ | |
url: "http://example.com/", | |
success: function(data) { | |
/** | |
* Continue the propagation of the queue by resolving this.dfd | |
*/ | |
this.dfd.resolve(); | |
}, | |
error: function() { | |
this.dfd.reject(true); | |
} | |
}).add({ | |
url: "http://example.com/", | |
success: function(data) { | |
/** | |
* Stop propagation of the queue by rejecting this.dfd. If reject() is | |
* passed true as an argument then the rest of the requests in the queue | |
* will be rejected. If you need to do cleanup a request is rejected, | |
* pass a cleanup callback as the second argument to add(). | |
*/ | |
this.dfd.reject(true); | |
} | |
}).add({ | |
url: "http://example.com/", | |
success: function(data) { | |
// This AJAX request will not be made. | |
} | |
}, function() { | |
// This cleanup function will be called. | |
}).run(); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment