Last active
August 27, 2022 07:41
-
-
Save tiagopassinato/712c3a98cdd435235faf42916011d859 to your computer and use it in GitHub Desktop.
NodeJS Async-lock example
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
/** | |
* Preventing dead-locks, using async-lock by key | |
*/ | |
var AsyncLock = require('async-lock'); | |
var lock = new AsyncLock(); | |
function operation(id) { | |
console.log(id + " calling operation"); | |
lock.acquire(id, function(done) { | |
console.log(id + " Running operation") | |
setTimeout(function() { | |
console.log(id + " Finishing operation") | |
done(); | |
}, 3000) | |
}, function(err, ret) { | |
console.log(id + " Freeing lock", ret) | |
}, {}); | |
} | |
operation('key1'); // will Run | |
operation('key1'); // will Wait the 1st | |
operation('key2'); // will Run Paralell with the 1st |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@NeilJ12 Were you able to create a function? I am looking for a similar function.