我在这篇博客中找到了一段完美运行的代码,但其中使用的Promise很难理解。
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();
}
}
}
表达式
new Promise(res => { begin = res; })
是否有效?Promise通常涉及在“某个东西”上调用resolve
为什么
const unlock = await this.lock();
会解析为一个函数?
res
是一个绑定方法,可以解决(仅限于)Promise对象。如果你真的想要,你可以拥有resolve函数。如果你只是想玩一下resolve,请参考我的这个答案。https://stackoverflow.com/questions/57106667/syntax-of-promises-in-javascript-is-confusing/57106943#57106943 - Nishantlet begin: (unlock: () => void) => void = unlock => {};
doesn't make any sense, that arrow function is never called but immediately overwritten in thenew Promise
executor. It really should be justlock(): PromiseLike<() => void> { return new Promise(begin => { this.mutex = this.mutex.then(() => { return new Promise(begin); }); }); }
- Bergi