UNPKG

@nent/core

Version:

Functional elements to add routing, data-binding, dynamic HTML, declarative actions, audio, video, and so much more. Supercharge static HTML files into web apps without script or builds.

42 lines (41 loc) 1.16 kB
/*! * NENT 2022 */ /* It's a mutex that allows you to dispatch a function that will be executed in order */ export 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(); } } }