简体   繁体   中英

How to wait with function execution until subscription is completed?

I want to subscribe to an Observable and then execute another function. My problem is, it takes a moment until the request is finished. However, the code just continues with its execution immediatly after the subscription has started.

I need some information that will be there after the Subscription is complete . Without that data, transformShopList() will fail. When I run the code, this is what happens.

How can you wait for the Subscription to finish, and then go on with the rest of the statements?

this.observable3.subscribe(
  ...
);
// wait here?
this.transformShopList();

You'll have this problem whatever you do in Javascript. Asynchronous tasks must be chained . Either with Promise , Observable or callback functions.

The right code is

this.observable3.subscribe((...) => {
  ...
  this.transformShopList();
});

An observable emits an event and your subscription receives it. Move your transform shop list inside the subscription response and it will execute when the observable emits.

https://angular.io/guide/observables

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