【发布时间】:2019-12-14 19:21:42
【问题描述】:
我在this blog 中找到了一段代码,它运行良好,但使用了难以理解的 Promises
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; })是否有效?承诺通常涉及在某事上致电resolve为什么
const unlock = await this.lock();会解析为函数?
【问题讨论】:
-
res是一个绑定方法,可以解析(仅那个)Promise 对象。如果你真的想要,你可以取得 resolve 函数的所有权。如果您只想玩下决心,请参阅我的这个答案。 stackoverflow.com/questions/57106667/… -
let begin: (unlock: () => void) => void = unlock => {};没有任何意义,该箭头函数永远不会被调用,而是会立即在new Promise执行程序中被覆盖。真的应该只是lock(): PromiseLike<() => void> { return new Promise(begin => { this.mutex = this.mutex.then(() => { return new Promise(begin); }); }); }
标签: javascript ecmascript-6 promise async-await es6-promise