Created
May 30, 2014 14:18
-
-
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
This file contains hidden or 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
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