mutex-js
Provides a promise-based mechanism for locking around code which requires synchronization (i.e. you may want to synchronize functions that span multiple iterations of the event loop).
Install
npm install --save mutex-js
Getting started
const Mutex = ; const mutex = ;mutex;
Example
Below, we call an async function run
several times with different args (the calls will run in parallel).
The function reads data from a file, appends the input to the data and finally writes the modified data back to the file.
Without synchronization, each call to run
may overlap the results of the previous one.
Wrapping the function implementation in a locking mechanism ensures that only one call is executing the critical section at a time.
const mutex = ; // reads file, returns a promise with file dataconst readFromFile = {...}// appends arg to data, returns a promise with modified dataconst appendData = {...}// writes data to file, returns a promiseconst writeToFile = {...} const run = mutex; Promiseall