简体   繁体   中英

AngularJs. Using $q.all for sending multiple post requests

I have an AngularJs app in which I need to make $http post calls in a loop. Here is my code:

          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!!!!");
          });

For some reason, it is not posting all the items in the collection. I am aware that browsers usually do not allow more than 6 async post calls. From what I understood, $q.all was a way around it. Also, even if I comment out the $q.all part, it doesn't matter because the post calls get executed nonetheless.

I would greatly appreciate any help!

Be aware that $q.all is not resilient . It will terminate with the first rejected promise. But that really isn't your problem.

You need to chain your posts to avoid the browser limit of simultaneous posts.

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

Notice, that for promiseMinusOne , the use of .catch and return in order to continue the list in the event of a rejection of one of the items.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM