0

My question is how to execute 3 functions(declared in service) in order:

   function1();
   function2();
   function3();

All functions contain http commands(e.g. put or get). that's why if I use code above function 3 will be executed before function 2. I tried to chain functions with then but that didn't help either.

1 Answer 1

2

You need to return a promise and then use promise chaining, because your functions are async.

function1().then(function(response) {
   /* executes function2, if function1 return success */
   function2().then(function(response) {
      /* executes function3, if function2 return success */
      function3();
   }
}

In the angular docs (https://docs.angularjs.org/api/ng/service/$q) you can see how to return a promise. For the case you use the $http or $resource provider: They always return a promise which you can use for your purpose.

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

2 Comments

Yes, thanks, is there some other way to do this then using then/promises?
$http is hardcoded async. You need to write your own provider to make synchronous calls. However this is a really bad idea because your UI is blocking.

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.