gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 10:33:26 25 4
gpt4 key购买 nike

我的 AngularJS Controller 中有以下接收器:

   // 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 而不会停止整个应用程序。

参见 - Angular's Q documentation

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

关于javascript - AngularJS : How to execute function in pre-defined order?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29105883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com