@nent/core
Version:
46 lines (43 loc) • 1.19 kB
JavaScript
/*!
* NENT 2022
*/
;
/* It's a mutex that allows you to dispatch a function that will be executed in order */
class Mutex {
constructor() {
this.mutex = Promise.resolve();
}
/**
* "The mutex is a promise that resolves to a promise that resolves to a function that unlocks the
* mutex."
*
* The mutex is a promise that resolves to a promise that resolves to a function that unlocks the
* mutex
* @returns A promise that resolves to a function that unlocks the mutex.
*/
lock() {
let begin = _unlock => { };
this.mutex = this.mutex.then(() => {
return new Promise(begin);
});
return new Promise(res => {
begin = res;
});
}
/**
* It takes a function as an argument, and returns a promise that resolves to the return value of
* that function
* @param {(() => T) | (() => PromiseLike<T>)} fn - (() => T) | (() => PromiseLike<T>)
* @returns A promise that resolves to the result of the function passed in.
*/
async dispatch(fn) {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
}
finally {
unlock();
}
}
}
exports.Mutex = Mutex;