Reputation: 11642
I have following receiver in my AngularJS Controller:
// 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:
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.
Upvotes: 0
Views: 94
Reputation: 1018
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.
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.
see - Angular's Q documentation
A service that helps you run functions asynchronously, and use their return values (or exceptions) when they are done processing.
Upvotes: 1