Skip to content

Instantly share code, notes, and snippets.

@mattbontrager
Last active July 17, 2018 20:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattbontrager/8bd4d25d014d2bc1c7c4ea3f324ac8e6 to your computer and use it in GitHub Desktop.
Save mattbontrager/8bd4d25d014d2bc1c7c4ea3f324ac8e6 to your computer and use it in GitHub Desktop.
Processing asynchronous operations (deferreds) in sequence, in a loop with jQuery.
/* * /
Due to target constraints, it had to be done with jQuery (no new hotness allowed).
It took me some time to figure this out so, I thought I'd store it here for reference.
/* */
var doSomeDeferredStuff = function doSomeDeferredStuff(dvcs) {
console.log('in doSomeDeferredStuff');
var deferreds = [];
$.each(dvcs, function(i, dvc) {
var meta = Devices.Store.getItem(dvc.type),
endpoint = meta.endpoints.device.replace(/\:device_id/, dvc.object_id),
device = Devices.All.getItem(dvc.object_id);
deferreds.push(
$.getJSON(endpoint).done(function(data) {
// update local copy
var detail = data;
for (var k in detail) {
if (k && detail.hasOwnProperty(k) && k !== '' && k !== null) {
device[k] = detail[k]
}
}
}));
});
return deferreds;
};
var deferreds = doSomeDeferredStuff();
$.when.apply(null, deferreds).done(function() {
console.log('all done! in sequence ;)');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment