// Initialize mutex objectvarMutex=require('mutex');varmutex=newMutex();// Acquire 'foo' for 10 secods (maximum)mutex.lock('foo',10000,function(err,locked,ttl){if(locked){// do something with 'foo' ...// free 'foo'mutex.free('foo');}else{// 'foo' is locked at the moment}})// Acquire 'foo' for 10 secods (maximum)mutex.isolate('foo',10000,functionisolated(callback){// do something with 'foo' ...// 'foo' will be freed atomaticallycallback(null,'some result');},functionafter(err,result){// failed to acquire 'foo'if(result===false){}// 'foo' was acquired and processedelse{console.log(result);// 'some result'}})Same as isolate() but it will retry to lock again and again until it will be freed.
// Acquire 'foo' for 10 secods (maximum)mutex.isolateRetry('foo',10000,functionisolated(callback){// do something with 'foo' ...// 'foo' will be freed atomaticallycallback(null,'some result');},functionafter(err,result){console.log(result);// 'some result'})Conditional isolation. If checkFn() returns 'mutex.continue' it will isolate, else it will not lock.
vara=true;// or 'false'// Acquire 'foo' for 10 secods (maximum)mutex.isolateCondRetry('foo',10000,functioncheck(callback){// If some conditionif(a){// We need to isolatecallback(null,mutex.continue);}else{callback(null,'cached')}},functionisolated(callback){// do something with 'foo' ...// 'foo' will be freed atomaticallycallback(null,'some result');},functionafter(err,result){// if a == true --> 'some result'// if a == false --> 'cached'console.log(result);})$ npm install mutex