Skip to content

Instantly share code, notes, and snippets.

@apaleslimghost
Created May 30, 2014 14:18
Show Gist options
  • Save apaleslimghost/6704695569ccd2bbbfa4 to your computer and use it in GitHub Desktop.
Save apaleslimghost/6704695569ccd2bbbfa4 to your computer and use it in GitHub Desktop.
Wrapper to ensure an async function runs in series when called multiple times
function gatedAsync(fn) {
var running = false, queue = [];
return function(...args) {
if(running) {
queue.push([run, args]);
} else {
run(...args);
}
function run(...args) {
running = true;
fn(...args, function() {
var next = queue.shift();
if(next) {
process.nextTick(() => {
var [f, args] = next;
f(...args);
});
}
running = false;
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment