1
<div ng-click="method1(); method2()> </div>

Here if the method1() calls the database / external service and gets the data. And method2() is some other behavior execution like UI bindings.
Suppose in case if there is a delay in getting the data from method1(), how to avoid or stop execution of method2() until method1() execution completes.

Note: I can't add method2() call from method1() due to some restrictions. Also I want to execute both these methods from the ng-click only.

4
  • 3
    ajax goes asyc so you must consider using its callback function .you cannot have 2 function calls in ng-click . Commented Feb 15, 2018 at 11:00
  • Use $q.defer() to assign an asynchronous callback. Perhaps you need to do it in method3() where you merge them and resolve your Promises Commented Feb 15, 2018 at 11:01
  • I've read your note but looks like your method2() depends on method1() so it's recommended to call it from the method1() itself using conditional structure. Commented Feb 15, 2018 at 11:09
  • Is anything stopping you from writing a single new function which will call method1() and method2() and call that single function from ng-click? Commented Feb 15, 2018 at 11:10

3 Answers 3

1

Call the method 2 in response of method1, like this

function method1() {
    service.getData().then(function(response) {
        //got the response here, do the operation and call method2 here
        method2()
    }, function() {});
}

If you call it giving any timeout, then it is not a sure solution. So call it in response.

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

Comments

1

Try with $timeout:

<div ng-click="method1()"></div>   
$scope.method1=function() {
    // calls the database / external service
    $timeout(function () {
        method2();
    }, 5000);
}

1 Comment

method1 is asynchronous, meaning it can take from few milliseconds to few minutes of processing. You can't just wait for it a specific / hardcoded amount of time. It should be resolved as a Promise (with a $q service) instead
1

you can do something like this

function method1() {
    API.getData().then(function(response) {
        // call method2 here after you receive response
        method2()
    }, function(error) {});
}

html

<div ng-click="method1()> </div>

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.