0

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.

3
  • You haven't shown us what stopAllSelectedSounds does. Commented Mar 17, 2015 at 17:49
  • does $scope.someSoundsArePlaying is returning a promise or something else Commented Mar 17, 2015 at 17:50
  • redrom, did my answer answered your question? Commented Mar 18, 2015 at 7:27

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.