Angularjs provides convenient method for waiting on multiple promises to be resolved in parallel.
Usually, I place all promises into an array, then wait on the array using $q.all
method. This
method can also wait on an object with promises as values. Let us try this under Node
Install and load angular
Latest versions of Angular library are available through NPM registry
npm info angular
npm install angular
Angular NPM installation comes with jsdom, and thus can be loaded directly from Node environment
1 | var angular = require('angular'); |
We can grab the $q
service directly without creating an application
1 | var $q = angular.injector(['ng']).get('$q'); |
$q.all(Array)
I typically create an array of promises by mapping values. The resolved argument is an array with single result per promise, in the same order as original.
1 | var numbers = [100, 20, 42]; |
We can mix promises and values in the array and the resolved array has expected order
1 | var promises = [ |
$q.all(Object)
Instead of waiting on an array, we can place promises into an object as values.
1 | var obj = { |
We can even mix promises and other value types in the same object.
The promise returned by $q.all(obj)
will be resolved with another object,
each promise value will be replaced with actual value, and non-promise values
will remain unchanged
1 | $q.all(obj).then(function (results) { |
Notice that the order of properties in the resolved object is different from original object. I think this is due to Angular copying non-promise values first.