简体   繁体   中英

Angular RXJS, finish observable before return

i want to know how to 'wait' without using async/await to finish observable and then return that value

// import {Observable, of} from 'rxjs';
getFirstQueue() {
  if (this.insideVar) {
    return of(this.insideVar);
  }
  this.http.get(this.createUrl(`some_resource`)).subscribe((someVar: any) => {
    this.insideVar = someVar;
  });
  return this.insideVar;
}

You can't return from a subscription. You have to return an Observable . A function higher up the stack will then subscribe to this observable.

You can use tap to perform the same side-effect you are currently doing in the subscribe body before returning.

getFirstQueue(): Observable<any> {
  if (this.activeQueue) {
    return of(this.activeQueue);
  }
  return this.http.get(this.createUrl(`some_resource`)).pipe(
    tap((someVar: any) => {
      this.insideVar = someVar;
    })
  );
}

It is not possible to go from asynchronous callback to synchronous context. For that you need to use async/await , but if you take a look at the decompiled code the async/await is just a syntactic sugar on top of Promises, so it only looks like it came from async to sync

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM