YoroDiallo YoroDiallo - 12 days ago 7
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
self.uploadTables(item)
})

this.uploadFiles(params).then(callback)

}
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
}


In
$q.all
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
var promises = [];
angular.forEach(form, function(item) {
      promises.push(self.uploadTables(item).then(uploadTableCallback));
})
promises(this.uploadFiles(params).then(uploadFilesCallback));
$q.all(promises).then(allCallback)

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() {
              promisesResolve++;
              if (promisesResolve == promisesToResolve) {
                  // all resolved
              }
          })
    })