【问题标题】:What is the equivalent of promise<void> in observables?什么是可观察对象中的 promise<void> 等价物?
【发布时间】:2020-08-21 07:00:00
【问题描述】:

我正在使用 angular,所以 typescript,并尝试从 observable 返回一个 promise。

这样做的正确方法是什么?

我试过了:

of(EMPTY).toPromise() // error: Promise<Observable<never>>' is not assignable to type Promise<void>

of(null).toPromise() // no error but not sure if it is the right way

of().toPromise // error: Promise<Observable<unknown>>' is not assignable to type Promise<void> 

更新:

//这是声明它的接口

export interface CustomStoreOptions extends StoreOptions<CustomStore> {   
   /** Specifies a custom implementation of the remove(key) method. */
    remove?: ((key: any | string | number) => Promise<void> | JQueryPromise<void>);   
}

所以叫:

let store = new CustomStore({     
        remove: key => {
          // return ...
        }
      });

【问题讨论】:

  • 你能发布整个函数声明吗,因为我认为错误是由于声明的返回类型和实际返回类型不匹配造成的。

标签: angular typescript promise observable


【解决方案1】:

你可以这样写得到Promise&lt;void&gt;的等价物

 of(void(0))

您也可以创建一个不发出数据的主题

 const s = new Subject<void>();
 s.next(void(0));

【讨论】:

  • 为什么不of(undefined)of(void(0)) 会迷惑人的。
  • 是的,是一样的。实际上 undefined === void(0) 评估为真。我建议这个 void(0) 的原因是因为 Promise 的处理方式与 Promise 不同。而且由于问题想要有一个 Promise ,因此使用 let x: Promise = of(undefined).toPromise() 比使用 let x: Promise = of(void(0) 更令人困惑).toPromise() 区别很细微,但是由于类型有void,所以我使用void(0)。
猜你喜欢
  • 2019-10-01
  • 2016-09-12
  • 2020-10-11
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-10
相关资源
最近更新 更多