wantToBeAProgrammer
wantToBeAProgrammer

Reputation: 179

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() {
            let promise = null;
            let sub = someService.someObservable.subscribe(async () => {
               promise = await getDataFromApi()
            })
            subscriptions.push(sub)
            return promise;
        }

The first goal is i need to store subscription in global sub array. The second goal is when i get response with status 400 - I dont want to open modal. Only when i get 200 and everything is allright i want modal to be opened.

function async load() {
  const promise = await helpMe();
  openModal();
}

Upvotes: 2

Views: 4268

Answers (3)

KARTHIKEYAN.A
KARTHIKEYAN.A

Reputation: 20088

We will use Promise to return the subscribed Observabal value in the following way

const getUser = () => new Promise((resolve, reject) => {
    return UserInfoService().subscribe({
        err: err => reject(err),
        next: res => resolve(UpdateUserInfo(res)),
    })
})

Upvotes: 0

cyr_x
cyr_x

Reputation: 14257

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

Upvotes: 1

Bergi
Bergi

Reputation: 664538

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

Upvotes: 2

Related Questions