AngularJS : 如何按预先定义的顺序执行函数?

AngularJS : How to execute function in pre-defined order?

我的 AngularJS 控制器中有以下接收器:

   // Receive broadcast
        $rootScope.$on('setPlayListEvent', function(event, playListData) {
          if($scope.someSoundsArePlaying === true) {
             $scope.stopAllSelectedSounds();
          }
            $scope.setPlaylistToView(playListData);
        });

但似乎,setPlaylistToView 方法总是在代码之前被调用和执行:

 if($scope.someSoundsArePlaying === true) {
                 $scope.stopAllSelectedSounds();
              }

因此它会影响方法的结果。

请问,如何设置函数的“执行顺序”?像 resolve..then..

感谢您的任何建议。

Javascript 是单线程的,因此您不想占用线程,因此处理您的问题的一种可能方法是使用承诺。

我会按以下方式编写代码:

function stopAllSelectedSounds() {
  var deferred = $q.defer();

  //Perform logic

  //if logic performed successfuly
  deferred.resolve();

  //if logic failed
  deferred.reject('reason is blah');

  return deferred.promise;
}

$scope.stopAllSelectedSounds().then(function() {
  alert('Success');
  $scope.setPlaylistToView(playListData);
}, function(reason) {
  alert('Failed ' + reason);
});

只有当 stopAllSelectedSounds 成功执行时,您才会执行 setPlaylistToView 而不会停止整个应用程序。

见 - Angular's Q documentation

A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.