我有一系列方法,这些方法取决于其他方法的完成。
process1(data: string) : Observable<string> {
this.dataservice.process(data).subscribe(
(response) => {
return response.data;
}
);
}
main(data: string) : string {
var process1Data: string = process1(data);
// I would like to wait for process1 method to complete before running process2
// I do not want to include process2 inside subscribe of process1 because I have to make few more method calls
var process2Data: string = process2(process1Data);
var process3Data: string = process3(process2Data);
...
}
如何在调用下一个方法(process2,process3)之前等待可观察对象完成? (类似于C#中的await)
最佳答案
您可以尝试这样的事情...
main(data: string) : string {
process1Data$: Observable<string> = process1(data)
.take(1)
.switchMap((process1Data) => return process2(process1Data);
.
.
.
}
显然,
take(1)
假定process1(...)
解析为单个值并停止。之后,将switchMap
转换为process2
,这意味着它将开始发出process2
给出的可观察值。另一方面,如果您希望对
process2
发出的每个结果运行process1
,则只需删除take(1)
即可。关于javascript - 等待观察完成,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45354940/