2

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

3 Answers3

2

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();
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

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();
}
cyr_x
  • 13,987
  • 2
  • 32
  • 46
0

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)),
    })
})
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133