How to wait inside an RxJS subscription method

Inside the RxJS object, a callback is signed, I want awaitin a function async. The following is sample code that the typescript transporter complains about saying:

Error: (131, 21) TS2304: Cannot find the name "wait".

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
  });
}

I usually see this when trying to call a wait inside a function async. Should I somehow do a subscribe callback async, or am I going to do it wrong? The function saveToDatabaseis equal asyncand returns a promise resolving the primary key of the database that was written.

+12
source share
7 answers

await Promise Observable.


CF Tweet :

enter image description here


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();

:
enter image description here

+7

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

const title = await new Promise<string>(resolve => 
  this.translate.get('MYBOOK-PAGE.PAGE_TITLE')
   .subscribe(translated => {
     resolve(translated)
   }));

,

: , , .. , . .

: toPromise (). :

const title = await this.translate.get('MYBOOK-PAGE.PAGE_TITLE').toPromise();

+3

:

ngOnInit() {
  this.subscriber = dateSubscription.subscribe((date: Date) => {
      (async () => {
          let dbKey = await this._someService.saveToDatabase(someObject);
          // ... some other code here
      })();
  });
}
+1

, . , , await setTimeout() Observable, RxJS interval() .

:

import { interval } from 'rxjs';
...

// inside your method
const source = interval(100);
    source.subscribe(x => {
        subject.next(CONNECTIONS_DATA);
        subject.complete();
});
return subject;

RxJS: https://rxjs-dev.firebaseapp.com/guide/subject#reference-counting

, , - .

+1

await , await a Promise. .toPromise() . :

async ngOnInit() {
  const date = await dateSubscription.toPromise();      
  let dbKey = await this._someService.saveToDatabase(someObject);
}

await dateSubscription, Date. , .

, angular ngOnInit, . JavaScript TypeScript . , ngOnInit awaiter, (). angular . , .

0

async ngOnInit() { } - , Angular OnInit. void:

 export interface OnInit { ngOnInit(): void; }

- dateSubscription, Observable.fromPromise

 dateSubscription
 .flatMap(x=>
      Observable.defer(Observable.fromObservable(this._someService.saveToDatabase(someObject)))
   ).subscribe()
-1

Source: https://habr.com/ru/post/1676790/


All Articles