@techmely/utils
Version:
Collection of helpful JavaScript / TypeScript utils
32 lines (28 loc) • 599 B
JavaScript
/*!
* @techmely/utils
* Copyright(c) 2021-2024 Techmely <techmely.creation@gmail.com>
* MIT Licensed
*/
// src/mutexLock.ts
var MutexLock = class {
#mutex = Promise.resolve();
lock() {
let begin = () => {
};
this.#mutex = this.#mutex.then(() => new Promise(begin));
return new Promise((res) => {
begin = res;
});
}
async dispatch(fn) {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
} catch (error) {
throw new Error("Dispatch failed!");
} finally {
unlock();
}
}
};
export { MutexLock };