Return promise value from observable subsciption

女生的网名这么多〃 提交于 2020-04-30 05:56:25

问题


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

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



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


来源:https://stackoverflow.com/questions/56834905/return-promise-value-from-observable-subsciption

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!