如何使用$ q.all forEync forEach请求?

时间:2016-11-25 12:34:56

标签: angularjs promise angular-promise q

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

y0 = ppval(My_pp,x0)

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?但是我不能做那个我在forEach中调用的uploadTables。完成uploadFiles和uploadTables后如何调用回调函数?

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:-1)

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

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) {
    }
);