[Fixed] How to await inside RxJS subscribe method


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:

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

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.


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

CF this Tweet from Ben Lesh :

enter image description here

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`),

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

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

Output :
enter image description here

Leave a Reply

(*) Required, Your email will not be published