You can use $ q.all to wait for the completion of several non-synchronous events (promises).
$scope.ticket_stats = function() { // list of all promises var promises = []; //cleaning variables $scope.data_set = []; $scope.closed_tickets = []; //fetching time stamps (epoch) $scope.time_frame = time_period.days(7); //calling data using time stamps angular.forEach($scope.time_frame, function(item) { // create a $q deferred promise var deferred = $q.defer(); //debug console.log(item); tickets.status("closed", item).success(function(data) { console.log(data); $scope.closed_tickets.push(data[0].datapoints[0][0]); // promise successfully resolved deferred.resolve(data); }); // add to the list of promises promises.push(deferred.promise); }); // execute all the promises and do something with the results $q.all(promises).then( // success // results: an array of data objects from each deferred.resolve(data) call function(results) { $scope.data_set.push($scope.closed_tickets); }, // error function(response) { } ); }
First, deferred represents a piece of code that will execute an unknown amount of time to execute (asynchronous). deferred.resolve(data) simply states that the code is complete. The data can be any, objects, strings, any, but usually it is the result of your asynchronous code. In the same way, you can reject a promise with deferred.reject(data) (maybe the error was thrown by the server). Again, the data can be anything, but there should probably be an answer to the error.
deferred.promise just returns a promise object. The Promise object allows you to set .then(successFunction, errorFunction) so that you know that part of the code has finished executing before proceeding to successFunction (or errorFunction if it fails). In our case, $q has a .all method, which waits for the promises array to complete, then gives the results of all promises as an array.
Remember to enter the $q service.
csbarnes
source share