angular – 如何等待RxJS内部订阅方法
发布时间:2020-12-17 08:20:52 所属栏目:安全 来源:网络整理
导读:在RxJS主题的??订阅回调中,我想等待异步函数.下面是打字稿发布者抱怨说的代码示例: Error:(131,21) TS2304:Cannot find name ‘await’. async ngOnInit() { this.subscriber = dateSubscription.subscribe((date: Date) = { let dbKey = await this._someS
在RxJS主题的??订阅回调中,我想等待异步函数.下面是打字稿发布者抱怨说的代码示例:
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 }); } 通常我在尝试在非异步函数中调用await时会看到这一点.我是否需要以某种方式使订阅回调异步,或者我是否会犯这个错误?函数saveToDatabase是异步的,并返回一个解析为写入的数据库主键的promise.
您不需要使用等待,也不需要将Promise转换为Observable.
来自Ben Lesh的CF Tweet: 这是一个带有saveToDatabase函数模拟的例子: 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(); 输出: (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |