如何在调用另一个函数之前确保函数已完成 - 承诺链式Angular JS?

时间:2016-12-19 20:18:36

标签: javascript angularjs cordova ionic-framework

我已经构建了一组功能,可以检查是否有为iOS安排的当前通知,如果有,我想取消它们并重新安排它们。如果有计划项目,则会返回以下逻辑,如果有,则会开始取消并重新计划。问题是,它们都显示成功并且控制台日志显示这一点,但重新安排功能似乎没有重新安排它们。有没有办法确保在尝试重新安排之前删除它们?我唯一的猜测是,在完成删除之前,我会尝试重新安排。

if (isIOS){


      var getScheduled = function() {
        $cordovaLocalNotification.getAllScheduled().then(function (scheduledItems) { 
          $scope.scheduledContainer = scheduledItems;
          $scope.scheduledItems = scheduledItems;
            if($scope.scheduledItems.length < 1) {
              console.log('no previously scheduled items.')
              return;
            } else {
              cancelAll();
              console.log("there are items here.")
            }

        })
      }
      getScheduled();

      // If there are notifications, cancel and reschedule.

      var cancelAll = function() {
        console.log('we made it to the cancel function');
        // Cancell All
        $cordovaLocalNotification.cancelAll().then(function (result) {
            console.log('They Cancelled');
            rescheduleAll();
        });
      }

      var rescheduleAll = function() {
        //Reschedule All
            $cordovaLocalNotification.schedule($scope.scheduledItems).then(function() {
              console.log('Successfully Scheduled');

            });
      }

}

2 个答案:

答案 0 :(得分:2)

在承诺完成后使用finally执行函数:

var cancelAll = function() {
    console.log('we made it to the cancel function');
    // Cancell All
    $cordovaLocalNotification.cancelAll().then(function (result) {
        // This is the success handler
    }, function(err) {
        // This is the error handler
    }).finally(function() {
        console.log('They Cancelled');
        rescheduleAll();
    });
}

答案 1 :(得分:1)

你不能使用.success承诺并链接这些功能吗?

var function1 = function() {
     //do something
}.success(function () {
    function2();
}

var function2 = function () {
    //do something
}