在Javascript Promise中返回'resolve'函数

4

我在这篇博客中找到了一段完美运行的代码,但其中使用的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 - Nishant
1
let begin: (unlock: () => void) => void = unlock => {}; doesn't make any sense, that arrow function is never called but immediately overwritten in the new Promise executor. It really should be just lock(): PromiseLike<() => void> { return new Promise(begin => { this.mutex = this.mutex.then(() => { return new Promise(begin); }); }); } - Bergi
1个回答

3

这是一个有效的表达式吗?Promise通常涉及在某个地方调用resolve...

是的,它将resolve函数存储在全局的begin变量中。然后当执行new Promise(begin)时,它调用begin函数并因此解决它。

为什么const unlock = await this.lock();会解析为一个函数?

因为beginnew Promise以该新Promise的解析器函数(begin(resolve, reject))调用。由于begin本身是一个解析器,它将返回的Promise解析为另一个promise的解析器函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接