0

I have the following code that doesn't work:

 $scope.function_A();
 $scope.function_B();

and this DOES work:

 $scope.function_A();
 $timeout(function(){
     $scope.function_B();
 }),100;

This is due to the fact that function_B refers to a directive that hasn't been created yet by Angular. I believe that's why using $timeout fixes the problem.

My issue is: how to be sure that the 100 millisecond timeout is correct and will always work? Is it better to somehow detect that function_A finished instead of using $timeout?

1
  • You might need to work with Promises if your functions have a delay. Try using $q promises. This way you can call another function after the first one resolves asynchronously. Commented Oct 16, 2017 at 14:02

2 Answers 2

1

You can use Promises.

If you require function A to finish it's work, before calling function B, it is a good idea to make it return a promise. Some angular services have methods that already return a Promise, e.g. $http.get. By using $q you can prepare your own promises. For example:

$scope.function_A = function() {
  //function code
  return $q.when();
}

$scope.function_A().then(function() {
  $scope.function_B();
});

Read more about $q and Promises here

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

Comments

1

Use the callback mechanism

$scope.function_A(callback){
  // your implementation
  callback() // add it at the end
}

Now call function_B inside function_A

$scope.function_A(function(){
  $scope.function_B();
});

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.