[英]AngularJS : How to execute function in pre-defined order?
I have following receiver in my AngularJS Controller: 我的AngularJS控制器中有以下接收者:
// Receive broadcast
$rootScope.$on('setPlayListEvent', function(event, playListData) {
if($scope.someSoundsArePlaying === true) {
$scope.stopAllSelectedSounds();
}
$scope.setPlaylistToView(playListData);
});
But it seems, that method called setPlaylistToView is always called and executed before the code: 但是似乎总是在代码之前调用并执行名为setPlaylistToView的方法:
if($scope.someSoundsArePlaying === true) {
$scope.stopAllSelectedSounds();
}
And so it can affect the result of the method. 因此,它可能会影响方法的结果。
I would like to ask, how can i set " execution order" of functions? 我想问一下,如何设置功能的“执行顺序”? Something like resolve..then..
诸如解决..然后..
Thanks for any advice. 感谢您的任何建议。
Javascript is single threaded so you don't want to hold the thread, therefor a possible way to handle your issue is using a promise. Javascript是单线程的,因此您不想保留线程,因此,处理问题的一种可能方法是使用promise。
I would have write the code in the following way: 我将以以下方式编写代码:
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);
});
This way only when stopAllSelectedSounds is successfully executed you will execute setPlaylistToView without halting the entire app. 这样,仅当成功执行stopAllSelectedSounds时,才将执行setPlaylistToView而不停止整个应用程序。
see - Angular's Q documentation 参见-Angular Q文档
A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
一种服务,可帮助您异步运行函数,并在处理完成后使用它们的返回值(或异常)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.