延期承诺 [英] Deferred that extends Promise

查看:100
本文介绍了延期承诺的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何实现扩展Promise的Deferred Promise?重要的是,将Promise扩展到期望典型Promise的类型安全使用。

How to implement a Deferred promise that extends Promise? It's important to extend Promise for type-safe usage where a typical Promise is expected.

后续实施

export class Deferred<T> extends Promise<T> {                                   
  public _resolveSelf;
  public _rejectSelf;                                                           
  constructor() {
    super(
      (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject
      }
    )
  }                                                                             
  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }                        
}

抛出 TypeError:_this undefined

此Typescript游乐场,您可以看到编译的javascript很有趣。在第15行中,在声明 _this 时,已经分配了其属性。

In this Typescript playground, one can see that the compiled javascript is funny. In line 15, during declaration of _this already its properties are being assigned.

推荐答案

export class Deferred<T> implements Promise<T> {

  private _resolveSelf;
  private _rejectSelf;
  private promise: Promise<T>

  constructor() {
    this.promise = new Promise( (resolve, reject) =>
      {
        this._resolveSelf = resolve
        this._rejectSelf = reject

      }
    )
  }

  public then<TResult1 = T, TResult2 = never>(
    onfulfilled?: ((value: T) =>
      TResult1 | PromiseLike<TResult1>) | undefined | null,
    onrejected?: ((reason: any) =>
      TResult2 | PromiseLike<TResult2>) | undefined | null
    ): Promise<TResult1 | TResult2> {
      return this.promise.then(onfulfilled, onrejected)
    }

  public catch<TResult = never>(
    onrejected?: ((reason: any) =>
      TResult | PromiseLike<TResult>) | undefined | null
    ): Promise<T | TResult> {
      return this.promise.then(onrejected)
    }

  public resolve(val:T) { this._resolveSelf(val) }
  public reject(reason:any) { this._rejectSelf(reason) }

  [Symbol.toStringTag]: 'Promise'

}

然后 catch 的方法签名-从 Typescript的Promise接口粘贴并化妆品清理。 [Symbol.toStringTag] 行对于Typescript来说也是必须的,尽管您只能从编译器中找到。

Method signatures of then and catch copy-pasted from Typescript's Promise interface and cosmetically cleaned up. The [Symbol.toStringTag] line is also necessary for Typescript to consider this a Promise, though you only find that out from the compiler.

这篇关于延期承诺的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆