【发布时间】:2020-10-09 20:56:23
【问题描述】:
我对 observables 有一个问题。我的情况是,我订阅了主题,我想在成功的可观察响应中运行一个函数。一旦我的函数(foo)完成(这个函数必须完成才能在成功响应中继续逻辑),我想将 .next() 方法传递给我的另一个主题。我的问题是,我想不通,我怎么能等到我的函数 foo 完成并返回值。如果我在另一个主题上调用 setTimeout 到我的 .next() 方法,则一切正常。我只是想避免 setTimeout。 我的代码架构是:
this.customService.customSubject$.subscribe((response) => {
this.someValueNeededInFoo = response;
this.foo(); //I need to wait for this function to be executed until I move on
this.customService2.anotherSubject$.next(true); //That will be great if I can wait for this as well
this.customService2.thirdSubject$.next(response); //This should invoke last
});
foo() {
//do some logic stuff
return value;
}
如果我像这样在订阅中使用我的代码:
this.customService.customSubject$.subscribe((response) => {
this.someValueNeededInFoo = response;
this.foo(); //I need to wait for this function to be executed until I move on
setTimeout(() => {
this.customService2.anotherSubject$.next(true); //That will be great if I can wait for this as well
this.customService2.thirdSubject$.next(response); //This should invoke last
}, 1000);
});
然后一切正常。我想避免 setTimeout,因为在我的情况下它并不可靠。任何人都可以指导我,我可以在这里做什么,以进行这些函数调用链? 谢谢!
【问题讨论】:
标签: asynchronous rxjs