Book Image

Mastering JavaScript Promises

Book Image

Mastering JavaScript Promises

Overview of this book

Table of Contents (16 chapters)
Mastering JavaScript Promises
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Concurrency in Angular.js


We all want to achieve maximum output at a single slot of time by asking multiple services to invoke and get results from them. Angular.js provides this functionality via its $q.all service; you can invoke many services at a time and if you want to join all/any of them, you just need then() to get them together in the sequence you want.

Let's get the payload of the array first:

[ 
  { url: 'myUr1.html' },
  { url: 'myUr2.html' },
  { url: 'myUr3.html' }
]

And now this array will be used by the following code:

service('asyncService', function($http, $q) {
     return {
       getDataFrmUrls: function(urls) {
         var deferred = $q.defer();
         var collectCalls = [];
         angular.forEach(urls, function(url) {
           collectCalls.push($http.get(url.url));
         });

         $q.all(collectCalls)
         .then(
           function(results) {
           deferred.resolve(
             JSON.stringify(results)) 
         },
         function(errors) {
...