I'm using Angular's $q service to make async requests. I have 2 requests like so (assume I have an angular service named MyService that handles these requests):
MyService.Call1().then(function() {
//do all the first callback's processing here without waiting for call 2
});
MyService.Call2().then(function() {
//wait for results of first callback before executing this
});
I have no guarantee that the second call will finish after the first, but I need the results of call 1 in order to do processing in call 2. I understand that I could chain the promises together, meaning that call 2 waits for call 1 to finish before the request is made, but I want to fire both requests at the same time since I have all the data required to do so. What's the best way to do that?
Edit: I can use the results of the first call immediately. They drive some charts on my page. I don't want the first call to wait on the second call to do its processing. I think that rules out mechanisms like $q.all()
You can do both calls in parallel with all
$q.all([MyService.Call1(), MyService.Call2()]).then(function() {
// ...code dependent on both calls resolving.
});
Edit: In response to a comment, there are two things that might interest you. If you pass an array to all, you will find an array of resolutions as the first argument of your function inside of then. If, instead, you pass an object to all, you will find an object as your first argument with keys matching the same keys you passed into all.
$q.all([MyService.Call1(), MyService.Call2()]).then(function(arr) {
// ...code dependent on the completion of both calls. The result
// of Call1 will be in arr[0], and the result of Call2 will be in
// arr[1]
});
...and with objects
$q.all({a: MyService.Call1(), b: MyService.Call2()}).then(function(obj) {
// ...code dependent on the completion of both calls. The result
// of Call1 will be in abj.a, and the result of Call2 will be in
// obj.b
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With