1
 $scope.SaveAuditItems = function (audit) {
    var isError = false;
    $scope.isProcessing = true;
    var defer = $q.defer();
    var promises = [];

    for (var siteCounter = 0; siteCounter < audit.SessionSiteList.length; siteCounter++) {
        for (var itemCounter = 0; itemCounter < audit.SessionSiteList[siteCounter].AuditItemList.length; itemCounter++) {
            var item = audit.SessionSiteList[siteCounter].AuditItemList[itemCounter];

            item.TotalItems = audit.SessionSiteList[siteCounter].AuditItemList.length;
            item.CurrentItem = itemCounter;

            promises.push($scope.submitaudit(item));
        }
    };
     //It appears to be running all the promises in the array in parrallel then running CloseAudit.
        $q.all(promises).then(
            function (response) {
                $scope.CloseAudit(audit.AuditSessionId).then(function () {
            },
            function(){
                alert("done");
            },
            function(){
                alert("done");
            }
            );
        }).catch(function (exception) {
            $scope.Loading("Could not submit audit session #'+ audit.AuditSessionId +' , please try again.", 2000);
        });


}

How do make the promises run in consecutive order? It causes race conditions on the server data is being submitted to? This angular 1 code.

How do i use then when i do not know how many promises i will be running in sequence? All other answers use then but are always predefined count of promises. I cannot have a then within a then for ever..i can't seem to comprehend how i do this.

-------------------------------------edit 2---------------------------------------------

  $scope.SaveAuditItems = function (audit) {
    $ionicLoading.show({
        template: '<i class="icon ion-loading-c"></i>Please wait..Sending Item ( 1 Of ' + $scope.AuditItemCounter + ' )',
    }).then(function () {});
    var isError = false;
    $scope.isProcessing = true;
    var defer = $q.defer();
    var promises = [];

    for (var siteCounter = 0; siteCounter < audit.SessionSiteList.length; siteCounter++) {
        for (var itemCounter = 0; itemCounter < audit.SessionSiteList[siteCounter].AuditItemList.length; itemCounter++) {
            var item = audit.SessionSiteList[siteCounter].AuditItemList[itemCounter];

            item.TotalItems = audit.SessionSiteList[siteCounter].AuditItemList.length;
            item.CurrentItem = itemCounter;
            // $scope.Loading('Sending Item ( ' + item.CurrentItem + ' Of ' + item.TotalItems + ' )..', 0).then(function () {

            promises.push($scope.submitaudit(item));



            ConsoleLogger.AddLog('Sent Item ( ' + item.CurrentItem + ' Of ' + item.TotalItems + ' )');

            //Loading.show({ template: '<i class="icon ion-loading-c"></i>Sending Item ' + item.CurrentItem + ' of ' + item.TotalItems + ' ', }).then(function () { });
            $scope.Loading('Sent item ( ' + item.CurrentItem + ' Of ' + item.TotalItems + ' )', 0).then(function () {});


        }
    }

    var all = promises.reduce(function (cur, next) {
        return cur.then(next);
    }, Promise.resolve(true));


    all.then(function (a) {
        $ionicLoading.show({
            template: '<i class="icon ion-loading-c"></i>Finalising your audit..'
        }).then(function () {
                $scope.CloseAudit(audit.AuditSessionId).then(function () {
                    ConsoleLogger.AddLog('Audit submitted successfully.');
                });
            },
            function () {
                alert("doneeee");
            },
            function () {
                alert("done");
            }
        );
    });

enter image description here

You can see in the timing that the promises are not running in sequence as expected? What am i missing? I made the promises with a timeout of 7 seconds.. The closeaudit should have run after all the promises had returned but not happening for me!

GOT IT WORKING BY CHNAGING promises.push($scope.submitaudit(item)); TO

 promises.push(function(){return $scope.submitaudit(item)});
user2520306
  • 27
  • 1
  • 9

1 Answers1

1

Here is a quick example how to do it. Reduce all promises from the array one by one, the reduce function will chain then() of each promise. It will start with first after the first has resolved it will call second and so on ... to the end ;].

var promises = [
 function() { return new Promise(function(resolve, reject) {
   setTimeout(function() {
     console.log('resolve promise 1 after 3sec');
     resolve('promise 1');
    }, 3000)
  })},
  function() { return new Promise(function(resolve, reject) {
   setTimeout(function() {
     console.log('resolve promise 2 after 1.5sec');
     resolve('promise 2');
    }, 1500)
  })},
  function() { return new Promise(function(resolve, reject) {
   setTimeout(function() {
     console.log('resolve promise 3 after 2sec');
     resolve('promise 3');
    }, 2000);
  })}];

var all = promises.reduce(function(cur, next) {
    return cur.then(next);
}, Promise.resolve(true));


all.then(function(a) {
    console.log('all are done!');
});
Yordan Nikolov
  • 2,598
  • 13
  • 16