Skip to content Skip to sidebar Skip to footer

Return Promise Value From Observable Subsciption

Is there any chance to return from helpMe function value from getDataFromApi() ? So far every time i call this function i get 'null' value. async function helpMe() {

Solution 1:

Passing an async function to subscribe is pointless - it throws away the returned promise, it doesn't wait for anything. You would need to use

new Promise((resolve, reject) => {
    someService.someObservable.subscribe(resolve, reject);
})

or just call the builtin toPromise method:

async function helpMe() {
    await someService.someObservable.toPromise();
    return getDataFromApi();
}

Solution 2:

Instead of using async/await feature, you could just go with plain rxjs. The switchmap operator might help you here:

public helpMe()
{
  return this.someService.someObservable.pipe(
    switchMap(result =>
    {
      return someDataFromApi();
    }),
    tap(resultFromApi => {
      // ... do something with `resultFromApi` from `someDataFromApi`.
    }),
  ).toPromise();
}

Post a Comment for "Return Promise Value From Observable Subsciption"