Skip to content

Instantly share code, notes, and snippets.

@felixlaumon
Created April 15, 2014 11:16
Show Gist options
  • Save felixlaumon/10723918 to your computer and use it in GitHub Desktop.
Save felixlaumon/10723918 to your computer and use it in GitHub Desktop.
// Wraps a promise-returning `fn` so that `fn` will only be invoked
// one after another (no 2 concurrent calls)
function sequential (fn) {
var lastPromise = $.Deferred().resolve().promise();
return function () {
var context = this;
var args = arguments;
lastPromise = lastPromise.then(function () {
return fn.apply(context, args);
});
return lastPromise;
};
}
var get = sequential(function (i) {
var dfd = $.Deferred();
setTimeout(function () {
console.log('done', i);
dfd.resolve();
}, 1000);
return dfd.promise();
});
get(1);
get(2);
setTimeout(function () {
get(3);
}, 500);
setTimeout(function () {
get(4);
}, 501);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment