Skip to content

Instantly share code, notes, and snippets.

@tiagopassinato
Last active August 27, 2022 07:41
Show Gist options
  • Save tiagopassinato/712c3a98cdd435235faf42916011d859 to your computer and use it in GitHub Desktop.
Save tiagopassinato/712c3a98cdd435235faf42916011d859 to your computer and use it in GitHub Desktop.
NodeJS Async-lock example
/**
* 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
@marce1994
Copy link

can you just jump if bussy?

@haraldreingruber
Copy link

haraldreingruber commented Mar 22, 2019

Thanks for the example. I guess on line 8 the parameter should be called 'id' right?

@CAVAh
Copy link

CAVAh commented Apr 8, 2019

@haraldreingruber Yes, and on line 17 the parameter should be called 'ret' instead 'uuid'

@CAVAh
Copy link

CAVAh commented Apr 8, 2019

@marce1994 You can check if is busy...

lock.isBusy();

@NeilJ12
Copy link

NeilJ12 commented Nov 16, 2020

how can I make a return in lock.aquire ?
i want to make an function with a operation in lock and return the result that I obtain in lock.

@kk2491
Copy link

kk2491 commented Jun 9, 2021

@NeilJ12 Were you able to create a function? I am looking for a similar function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment