【问题标题】:how to use $q.all for async forEach requests?如何将 $q.all 用于异步 forEach 请求?
【发布时间】:2017-04-09 20:51:26
【问题描述】:

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

    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后如何调用回调函数?

【问题讨论】:

  • 你不使用forEach。你改用map。

标签: angularjs promise angular-promise q


【解决方案1】:
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
              }
          })
    })

【讨论】:

  • 您对 $q.all 的实现是错误的,即如果其中一个 promise 被拒绝,它就会永远挂起。它也不收集结果。
  • 更像arr.reduce((p, c) => p.then(v => c), $q.resolve()) 并收集结果丑陋const results = []; arr.reduce((p, c) => p.then(v => results.push(v), c), $q.resolve()).then(() => results)
  • @Benjamin Gruenbaum 也许我需要处理来自 $q 的拒绝以解决“永远挂起”?因为这对我有用
  • @Banjamin,我并不是说 some1 需要使用我的实现。 (顺便说一句,如果某些东西被拒绝,它就可以正常工作 - 不会执行回调)如果它已经存在于 Angular 中,为什么还要写一些东西?只是想证明这一切都很简单。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2019-04-26
    • 2018-05-17
    • 2022-12-18
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多