简体   繁体   English

在Javascript Promise中返回'resolve'函数

[英]Returning 'resolve' function in Javascript Promise

I have found a piece of code in this blog that works perfectly but makes a use of Promises that is hard to understand 我在这个博客中发现了一段完美无缺的代码,但是使用了很难理解的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();
    }
  }
}
  • Is valid the expression new Promise(res => { begin = res; }) ? 表达式是否有效new Promise(res => { begin = res; }) Promises usually involve calling resolve on something 承诺通常涉及调用resolve 的东西

  • Why does const unlock = await this.lock(); 为什么const unlock = await this.lock(); resolve to a function? 解决一个功能?

Is it a valid expression? 这是一个有效的表达吗? Promises usually involve calling resolve on something ... 承诺通常涉及对某事做出决定......

Yes, it stores the resolve function in the global begin variable. 是的,它将resolve函数存储在global begin变量中。 Then when new Promise(begin) executes, it calls the begin function and thus resolves it. 然后当new Promise(begin)执行时,它调用begin函数并因此解析它。

Why does const unlock = await this.lock(); 为什么const unlock = await this.lock(); resolve to a function? 解决一个功能?

Because begin gets called by new Promise with the resolve function of that new Promise ( begin(resolve, reject) ). 因为begin由被称为new Promise与新的承诺的决心功能( begin(resolve, reject) )。 As begin is a resolver itself, it'll resolve the returned Promise to the resolver function of the other promise. 由于begin是一个解析器本身,它会将返回的Promise解析为另一个promise的解析器函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM