[英]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();
}
因此,它可能会影响方法的结果。
我想问一下,如何设置功能的“执行顺序”? 诸如解决..然后..
感谢您的任何建议。
Javascript是单线程的,因此您不想保留线程,因此,处理问题的一种可能方法是使用promise。
我将以以下方式编写代码:
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而不停止整个应用程序。
一种服务,可帮助您异步运行函数,并在处理完成后使用它们的返回值(或异常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.