简体   繁体   English

如何在订阅完成之前等待函数执行?

[英]How to wait with function execution until subscription is completed?

I want to subscribe to an Observable and then execute another function. 我想订阅一个Observable,然后执行另一个函数。 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. 如果没有该数据,transformShopList()将失败。 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. 无论你在Javascript中做什么,都会遇到这个问题。 Asynchronous tasks must be chained . 必须链接异步任务。 Either with Promise , Observable or callback functions. 使用PromiseObservable或回调函数。

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. 将您的转换商店列表移动到订阅响应中,它将在observable发出时执行。

https://angular.io/guide/observables https://angular.io/guide/observables

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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