Scipion Scipion - 4 months ago 43
TypeScript Question

Synchronizing nested subscribe in angular2

I have the following code which logs :

"foo2"
and then
"foo1"
:

a() {
b().then(() => {
console.log("foo2")
})
}

b() {
return webServiceCall().do(() => {
webServiceCall2().subscribe(() => {
console.log("foo1")
})
})
}


I would like to be sure that my
foo1
appears before my
foo2
.

How could I solve this issue ? Thanks !

Answer

You can be sure that foo1 appears before foo2 if you use chained promises.

If the order of webServiceCall1 and webServiceCall2 matters:

b() {
    return webServiceCall1().then(() => {
        return webServiceCall2().then(() => {
            console.log("foo1")
        })
    })
}

If the order of webServiceCall1 and webServiceCall2 doesn't matter, use Observable.forkJoin :

b() {
    return Observable.forkJoin(webServiceCall1,webServiceCall2).toPromise().then(() => {
        console.log("foo1"); 
    });
}