Up until now, I've been creating functions that return directly from HTTP get, and then calling .subscribe
on the return value. However, recently I've learned about Promise.all
, and would like to know how I can use it to wait for both HTTP gets to be completed.
Example of how I'm currently doing it:
function getCustomerList() {
return this.http.get("http://myapi.com/getCustomerList");
}
function otherFunction() {
this.getCustomerList().subscribe() {
data => {}, err => {}, () => {}
}
}
This seems to work OK, but I keep wondering if I could do something like this instead:
function getCustomerList() {
return this.http.get("http://myapi.com/getCustomerList").subscribe( data => {}, err => {}, () => {});
}
function getVendorList() {
return this.http.get("http://myapi.com/getVendorList").subscribe( data => {}, err => {}, () => {});
}
function getAllInfo() {
var p1 = getCustomerList();
var p2 = getVendorList();
Promise.All([p1, p2]);
console.log("This should not run until both have returned");
}
But it always runs right away. So I tried to use .toPromise()
in the get()
functions with .then()
, and it did the same thing. The only thing I haven't tried is maybe putting a .toPromise()
on the outer function.