如何在angularjs中顺序执行函数

时间:2016-09-12 13:41:39

标签: angularjs

想要使用angularjs顺序执行3个函数。

function doThis(callback){

                 $scope.db.transaction(function (transaction) {

                     transaction.executeSql("insert into tbl1(---) values (?,?,?)", []);

                 });              

             if (typeof callback === 'function') {

                 callback();
             }
         }

         function doThat() {

             $scope.db.transaction(function (transaction) {
                 transaction.executeSql("select * from tbl1 orderby col1 desc limit 1", [], function (transaction, result) {

                    //some code

                 });
             });
         }

         doThis(doThat);

首先想要执行doThis,而不是在完成doThis之后执行doThis,doThat将执行。

2 个答案:

答案 0 :(得分:0)

您可以使用AngularJS的承诺服务,名为$q

使用它的一种简单方法可以是上面的代码,但请查看我以前分享过的链接。

firstFunction.then(function() {
    // Will be call after firstFunction
});

答案 1 :(得分:0)

       function doThis(callback) {

             var executeOnSuccess = false;
             $scope.db.transaction(function (transaction) {

                 transaction.executeSql("insert into tbl1(---) values (?,?,?)", []);
          executeOnSuccess = true;
             });              

         if (typeof callback === 'function' && executeOnSuccess ) {

             callback();
         }
     }

     function doThat() {

         $scope.db.transaction(function (transaction) {
             transaction.executeSql("select * from tbl1 orderby col1 desc limit 1", [], function (transaction, result) {

                //some code

             });
         });
     }

     doThis(doThat);