1
testAngular();  //**(1º)**

function testAngular() {

        var uri = 'some_webmethod_url';

        var data = {
            "key": "anything"
        };

        var res = $http.post(uri, data);

        res.then(function (data) {

            console.log(data); //**(2º)**

        });

        console.log(data); //**(3º)**
}

console.log(data);  //**(4º)**

The actual sequence is 1º -- 3º -- 4º -- 2º; Why? And more importantly, how can I make this in that sequence? (1º -- 2º -- 3º -- 4º)

1 Answer 1

1

Since the 'then' is a callback and called asynchronously when the response from the server becomes available (after the POST request is completed). So the statement console.log(data); //**(2º)** will be executed only after the response is received but rest of other processing will continue.

If you want the order that you mentioned, you will have to make those statement as part of the callback. The other option is to make the callbacks synchronous which is not supported out of the box by Angular JS but you can look into the source code and make changes. This SO post might help you in that https://stackoverflow.com/questions/13088153/how-to-http-synchronous-call-with-angularjs

Or a small hack as mentioned in other SO post might help you AngularJs: Have method return synchronously when it calls $http or $resource internally though it's not recommended.

testAngular();  //**(1º)**

    function testAngular() {

            var uri = 'some_webmethod_url';

            var data = {
                "key": "anything"
            };

            var res = $http.post(uri, data);

            res.then(function (data) {

                console.log(data); //**(2º)**

                console.log(data); //**(3º)**
                console.log(data);  //**(4º)**
            });


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