Created
April 15, 2014 11:16
-
-
Save felixlaumon/10723918 to your computer and use it in GitHub Desktop.
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
// 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