parallelqall
Using q.all to handle all promises resolution
by Jimmy Chandra
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
<div id="app">
<App />
</div>
JavaScript
const { bootstrap, module } = angular;
class SomeAsyncService {
constructor($timeout) {
this.timeout = $timeout
}
DoSomethingAsync(id) {
console.log(`Starting async task ${id}...`);
const delay = 250 + Math.random()*1500;
return this.timeout(() => {
console.log(`Completed async task ${id} after ${delay.toFixed(2)} ms.`);
return id * 5;
}, delay);
}
}
class AppComponentController {
constructor(SomeAsyncService, $q) {
this.AsyncSvc = SomeAsyncService;
this.$q = $q;
}
DoParallelStuff() {
let tasks = [...Array(5).keys()]
.map(idx => this.AsyncSvc.DoSomethingAsync(idx + 1));
this.$q.all(tasks)
.then(t => {
console.log('All async tasks are completed.');
const tsum = t.reduce((a,c) => a + c, 0);
console.log(`Task results: ${t}`);
console.log(`Sum of all task results is ${tsum}.`);
});
}
}
const AppComponent = {
selector: 'app',
template: '<button ng-click="$ctrl.DoParallelStuff()">Do Parallel Tasks</button>',
controller: AppComponentController
};
module('myapp', [])
.service("SomeAsyncService", SomeAsyncService)
.component(AppComponent.selector, AppComponent);
const root = document.getElementById('app');
bootstrap(root, [ 'myapp' ])