Is this the right way to do promises in this instance?
Yes, it is.
The 10x logging seems like something is broken....., and the feared race condition appears to be a possibility....
Can someone explain what is going on here?
It's actually not broken. Like you suggest $q.all
waits for all promises to complete.
In:
$q.all([a,b,c,d]).then(function(){
// yes, this only runs after all of the promises fulfilled
});
Here is what happens:
You have a loop that runs 10 times:
- A calls from the entire loop all fulfill instantly.
- B calls from the entire loop all fulfill instantly.
- C call resolves
- The promise composed of the
$q.all
for that instance of a,b,c for the a (already resolved) the b (already resolved) and now the c - fulfilled.
- The promise composed of the
- Next c call resolves
- The promise composed of the
$q.all
for that instance of a,b,c for the a (already resolved) the b (already resolved) and now the c - fulfilled.
- The promise composed of the
And so on.
The only guarantee you have is that inside the loop that instance of $q.all([a,b,c]
will fulfill after its local a,b and c. Nothing else, nothing more.
If you want to hook on the aggregate promise of all the return values, you can of course perform a $q.all
on all ten of them.