如何在Angular JS

时间:2015-08-25 14:40:57

标签: angularjs foreach sequential

我正在尝试使用下面的代码顺序执行SQL命令列表。但我可以看到,从下面的方法不能保证顺序。什么是正确的方法?

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

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

创建一个函数executeNextQuery()并从then()

中递归调用它

答案 2 :(得分:0)

$ q.serial以更清洁的方式帮助实现了这一目标http://www.codeducky.org/q-serial/

        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 paidby where paid_exp not in (select exp_id from exp)';
        querylistfordeletegrp = [deletepaidbyentries, deleteapplicabletoentries, deletesettlements, deleteuserassociations, deletegrpquery, deleteexpensesofgrp, cleanup_applicable, cleanup_paidby];
        // solution
        var tasks = querylistfordeletegrp.map(function(query) {
            return function() {
                return DB.query(query, [grp_id]);
            };
        });
        $q.serial(tasks);