如何使用 $q.all 进行异步 forEach 请求?

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

我需要在完成 2 个请求后调用该函数。所以我尝试为此使用 $q.all 。我在 Angular 上有服务,它调用 submitForm,在提交之前我需要再做 2 个请求,在他们响应之后 - 发出 post 请求以提交表单。它看起来像这样:

    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
    } 

$q.all 中我想我需要像 $q.all(this.uploadFiles, this.uploadTables) 那样称呼它?但我不能那样做,因为我在 forEach 中调用了 uploadTables。完成uploadFiles和uploadTables后如何调用回调函数?

您可以return并在数组中收集承诺

var promises = [];


angular.forEach(form, function(item) {

    var deferred = $q.defer();
    //do your code
    deferred.resolve(result);

    promises.push(deferred.promise);
});

// execute all the promises and do something with the results
$q.all(promises).then(

    function(results) {
      //do your stuff
    },
    // error
    function(response) {
    }
);
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)

我还想注意 $q.all 中没有什么特别之处,您始终可以手动完成:

var promisesToResolve = arr.length;
var promisesResolve = 0;
    angular.forEach(arr, function(obj) {
          $http.post(obj).then(function() {
              promisesResolve++;
              if (promisesResolve == promisesToResolve) {
                  // all resolved
              }
          })
    })