Wait for you to see

I have a number of methods that depend on the completion of other methods.

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);

   ...

}

      

How can I wait for the observable to execute before calling the next method (process2, process3)? (looks like wait in C #)

+3


source to share


3 answers


You can try something like this ...

main(data: string) : string {

    process1Data$: Observable<string> = process1(data)
        .take(1)
        .switchMap((process1Data) => return process2(process1Data);
    .
    .
    .
}

      



Obviously, it take(1)

assumes that it proces1(...)

permits one value and stops. After that, it is from switchMap

to process2

, which means that it starts to emit everything that is observed from the process2. If, on the other hand, you want to process2

run from every result emitted by frmo process1, just remove take(1)

.

+3


source


You can use es6 async / await



async main(data: string): string {
    var process1Data: string = await process1(data).toPromise();
    var process2Data: string = process2(process1Data);
    ...
}

      

+2


source


You can use the rxjs concat statement. See the documentation here. concat

Basically it waits up to the first or source of observed returns and then executes the next one.

Update

You can also try carriers like switch or switchboard as per your requirement.

+2


source







All Articles