在RxJS主题的订阅回调中,我想等待异步函数.下面是打字稿发布者抱怨说的代码示例:
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 }); }
通常我在尝试在非异步函数中调用await时会看到这一点.我是否需要以某种方式使订阅回调异步,或者我是否会犯这个错误?函数saveToDatabase是异步的,并返回一个解析为写入的数据库主键的promise.
您不需要使用等待,也不需要将Promise转换为Observable.
来自Ben Lesh的CF Tweet:
这是一个带有saveToDatabase函数模拟的例子:
(和工作的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();
输出: