如何在RxJS订阅方法中等待 [英] How to await inside RxJS subscribe method

查看:328
本文介绍了如何在RxJS订阅方法中等待的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在RxJS主题的​​订阅回调中,我想在async函数上使用await.以下是打字稿翻译抱怨的一个代码示例:

Inside of an RxJS subject's subscribe callback, I want to await on an async function. Below is a code example which the typescript transpiler complains about saying:

错误:(131,21)TS2304:找不到名称等待".

Error:(131, 21) TS2304:Cannot find name 'await'.

async ngOnInit() {
  this.subscriber = dateSubscription.subscribe((date: Date) => {
    let dbKey = await this._someService.saveToDatabase(someObject);
    // wait for db write to finish before evaluating the next code
    // ... some other code here
  });
}

通常,当我尝试在非async函数中调用await时,会看到此消息.我是否需要以某种方式使订阅回调async还是要解决这个错误?函数saveToDatabaseasync,它向写入的数据库主键返回一个承诺解析.

Usually I see this when trying to call await inside a non async function. Do I somehow need to make the subscribe callback async or am I going about this wrong? The function saveToDatabase is async and returns a promise resolving to the database primary key that was written to.

推荐答案

您不需要使用await,也不需要将Promise转换为Observable.


CF这是来自Ben Lesh的推文:

You do not need to use await, nor need to convert your Promise to an Observable.


CF this Tweet from Ben Lesh :

这是一个模拟saveToDatabase函数的示例:
(以及正在工作的Plunkr: https://plnkr.co/edit/7SDLvRS2aTw9gYWdIznS?p=预览)

Here's an example with a mock for the function saveToDatabase :
(and the working Plunkr : https://plnkr.co/edit/7SDLvRS2aTw9gYWdIznS?p=preview)

const { Observable } = Rx;

const saveToDatabase = (date) =>
  new Promise(resolve =>
    setTimeout(() =>
      resolve(`${date} has been saved to the database`),
      1000));

const date$ = Observable.of(new Date()).delay(1000);

date$
  .do(x => console.log(`date received, trying to save it to database ...`))
  .switchMap(date => saveToDatabase(date))
  .do(console.log)
  .subscribe();

输出:

这篇关于如何在RxJS订阅方法中等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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