AngularJs。使用$ q.all发送多个帖子请求

时间:2015-11-27 22:32:28

标签: angularjs post promise angular-promise

我有一个AngularJs应用程序,我需要在循环中进行$ http post调用。这是我的代码:

          var promisesArray = [];
          for(i = 0; i < 28; i++) {
                 promisesArray.push($http({
                    method: "post",
                    url: "/studentanswers",
                    data: {
                        studentName: "abc",
                        answerImage: "sdf",
                        questionPrompt: 1
                    }
                }));
          }
          $q.all(promisesArray).then(function(data){
              console.log("success!!!!");
          });

由于某种原因,它没有发布集合中的所有项目。我知道浏览器通常不允许超过6个异步后置调用。根据我的理解,$ q.all是一种解决方法。此外,即使我注释掉$ q.all部分,也没关系,因为post调用仍然执行。

我非常感谢任何帮助!

1 个答案:

答案 0 :(得分:3)

请注意$q.all 不具弹性。它将以第一个被拒绝的承诺终止。但这确实不是你的问题。

您需要链接您的帖子,以避免浏览器限制同时发布帖子。

var promisesList = [];
var promiseMinusOne = $q.when();

for (var i = 0; i < 28; i++) {
    //begin IIFE closure
    function(i) {
        //chain off promiseMinusOne
        var httpPromise = 
             promiseMinusOne.catch (function (e) {
                 return e;
             }) .then (function (r) {
                 return $http({ method: "post",
                                url: "/studentanswers",
                                data: answerList[i]
                 })
             });
        promisesList.push(httpPromise);
        promiseMinusOne = httpPromise; 
    }(i);
    //end IIFE closure
};

var chainablePromise = 
    promiseMinusOne.catch (function (e) {
        return (e);
    }) .then (function (r) {
        //process the promisesList
    });

请注意,promiseMinusOne使用.catchreturn,以便在拒绝其中一项时继续使用该列表。

相关问题