I have found a piece of code in this blog that works perfectly but makes a use of Promises that is hard to understand
export class Mutex {
private mutex = Promise.resolve();
lock(): PromiseLike<() => void> {
let begin: (unlock: () => void) => void = unlock => {};
this.mutex = this.mutex.then(() => {
return new Promise(begin);
});
return new Promise(res => {
begin = res;
});
}
async dispatch(fn: (() => T) | (() => PromiseLike<T>)): Promise<T> {
const unlock = await this.lock();
try {
return await Promise.resolve(fn());
} finally {
unlock();
}
}
}
Is valid the expression
new Promise(res => { begin = res; })
? Promises usually involve callingresolve
on somethingWhy does
const unlock = await this.lock();
resolve to a function?