Skip to content

Instantly share code, notes, and snippets.

@creage
Created April 25, 2014 20:43
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 creage/11302611 to your computer and use it in GitHub Desktop.
Save creage/11302611 to your computer and use it in GitHub Desktop.
$.eachDeferred
(function ($, window, document, undefined) {
$.extend({
/*
* Iterates over elms array/collection using deferred callbacks.
* the function assigned for iterator should return promise.
* resolved promises notify the main deferred, so we can track each loop result.
* returns promise.
*/
eachDeferred: function (elms, c) {
if (!$.isArray(elms)) {
elms = $.makeArray(elms);
}
var that = this,
dfd = $.Deferred(),
i = elms.length,
next = function () {
setTimeout(function () { elms.length ? cb(elms.shift()) : dfd.resolve(that); }, 0);
},
cb = function (elm) {
$.when(c.call(elm, i - elms.length, elm)).always(function (result) {
dfd.notify(result);
next();
});
};
next();
return dfd.promise();
}
});
}(jQuery, window, document));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment