fortunee
fortunee

Reputation: 4352

Awaiting a Promise result within an Angular RxJS Observable Method

The method below is expected to be an Observable that needs some data from a promise function to continue execution.

    async function observableFunc(): Observable<string> {
      const response = await promiseFunc()
      return anotherObservableFunc(response)
    }

This throws an error because async functions are supposed to return a promise.

I tried to use .toPromise() but then I can’t do something using .pipe() later on like this:

observableFunc().pipe(...)

What's a dev posed to do here? 🤔

Upvotes: 0

Views: 297

Answers (3)

Shlok Nangia
Shlok Nangia

Reputation: 2377

Try this

promiseFunc(){
      return new Promise(function(resolve, reject) {
        resolve('start of new Promise');
      });
  }

create a new promise in this way

you can also wait for few seconds to try like this

promiseFunc(){
  return new Promise((resolve, reject) => {
    setTimeout(() => resolve("done!"), 1000)
  });
}

and its call will be like

async function observableFunc(){
      const response = await promiseFunc()
      // no do whatever you like as next statement will be executed after response gets it value

    }

Upvotes: 0

distante
distante

Reputation: 7025

You have to convert the promise to an observable

function observableFunc(): Observable<string> {
  return from(promiseFunc())
   .pipe(
      swithMapTo(anotherObservableFunc())
    );

}

I am assuming anotherObservableFunc returns an observable.

Upvotes: 2

Poul Kruijt
Poul Kruijt

Reputation: 71961

You can use from, which converts a Promise (among other things) to an Observable:

function observableFunc(): Observable<string> {
  return from(promiseFunc()).pipe(
    concatMap(() => anotherObservableFunc())
  );
}

I'm using concatMap, because it's more descriptive. It basically says, wait until the previous Observable completes (which a Promise does) and then subscribe to the other Observable.

Although in this case, there would be no difference in using mergeMap or switchMap. Semantically, the concatMap is a better fit

Upvotes: 2

Related Questions