YoroDiallo YoroDiallo - 1 year ago 96
AngularJS Question

how to use $q.all for async forEach requests?

I need to call the function after 2 request is done. So I try to use $q.all for this. I have service on Angular it calls submitForm, before submit I need to do 2 another request, and after they response - make post request to submit form. It looks like this:

submitForm : function(form, params) {
var self = this;
var callback = function () {
// this is submit post req

angular.forEach(form, function(item) {
// I search tables (type of field) and then send req for saving tables on backend


uploadFiles : function(params) {
// this func upload files before submit
uploadTables : function(params) {
// for uploading tables I have another service on backend, so I need another request, before submit

I guess I need to call it like
$q.all(this.uploadFiles, this.uploadTables)
? But I cant do that couse uploadTables I call in forEach. How can I call callback function after complete uploadFiles and uploadTables?

Answer Source
var promises = [];
angular.forEach(form, function(item) {

I want also to notice that there is nothing special in $q.all and you can always do it manually:

var promisesToResolve = arr.length;
var promisesResolve = 0;
    angular.forEach(arr, function(obj) {
          $http.post(obj).then(function() {
              if (promisesResolve == promisesToResolve) {
                  // all resolved
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download