Search code examples
angularjsasynchronoussynchronizationangularjs-service

Angular function syncronization


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.


Solution

  • 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.