Last active
August 29, 2015 14:04
-
-
Save zeekay/80e3bf54221e997f42a3 to your computer and use it in GitHub Desktop.
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
// Lock async function until complete. | |
function lock(fn) { | |
return function() { | |
var args = Array.prototype.slice.call(arguments, 0); | |
var cb = args.pop() || function(){}; | |
var that = this; | |
if (fn.locked) | |
return cb(new Error('locked!')) | |
args.push(function() { | |
fn.locked = false; | |
cb.apply(that, arguments); | |
}) | |
fn.locked = true; | |
fn.apply(that, args); | |
} | |
} | |
// Calls back with 'unlocked!' if there is no error. | |
var lockedFn = lock(function(cb) { | |
setTimeout(function() { | |
cb(null, 'unlocked!') | |
}, 100) | |
}) | |
// Our generic callback | |
function complete(err, res) { | |
if (err) | |
console.log('locked!') | |
else | |
console.log(res) | |
} | |
// Try to run multiple times! | |
lockedFn(complete) | |
lockedFn(complete) | |
lockedFn(complete) | |
// Wait til unlocked again | |
setTimeout(function() { | |
lockedFn(complete) | |
}, 200) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment