Search code examples
angularjsforeachsequential

How to sequentially execute sql statements in Angular JS


I am trying to execute list of SQL commands sequentially with below code. but i could see that sequence is not guaranteed from below approach. what woould be the right approach ?

deletegrpquery = 'delete FROM grp where grp_id=(?)';
deleteuserassociations = 'delete FROM grp_usr where grp_id=(?)';
deleteexpensesofgrp = 'delete FROM exp where exp_grp=(?)';
deletepaidbyentries = 'delete FROM paidby where paid_exp in ( select exp_id from exp where exp_grp=(?))';
deleteapplicabletoentries = 'delete FROM applicableto where applicable_exp in ( select exp_id from exp where exp_grp=(?)';
deletesettlements = 'delete from settlements where settlement_grp=(?)';
cleanup_applicable = 'delete FROM applicableto where applicable_exp not in (select exp_id from exp)';
cleanup_paidby = 'delete FROM applicableto where applicable_exp not in (select exp_id from exp)';

querylistfordeletegrp = [deletepaidbyentries, deleteapplicabletoentries, deletesettlements, deleteuserassociations, deletegrpquery,deleteexpensesofgrp, cleanup_applicable, cleanup_paidby];

angular.forEach(querylistfordeletegrp, function(query) {
  DB.query(query, [grp_id]).then(function(result) {
      console.log(query);
  });
})

Solution

  • var promise = $q.when();
    angular.forEach(querylistfordeletegrp, function(query) {
      promise = promise.then(function() {
        return DB.query(query, [grp_id]);
      });
    });