petko_stankoski
petko_stankoski

Reputation: 10723

Order of execution on code

function method1() {
    method2();
    var x = 1;
}

function method2() {
    $.ajax({
        type: "GET",
        async: true,
        url: "/MyController/MyMethod",
        success: function (data) {
            var y = 6;
        }
    });
}

Which happens first - the initialization of y or the initialization of x? Which would be the order of these two lines if the ajax call was sync instead of async?

method1 is called in the loading of the page.

Upvotes: 2

Views: 98

Answers (2)

PhonicUK
PhonicUK

Reputation: 13864

x will be initialized first (Unless somehow the HTTP response comes back before it's able to execute the next line, which is extremely unlikely). $.ajax is asynchronous and it will take time for the response to come back.

If you wanted to guarantee that y was initialized first, you'd do this instead:

function method1() {
    method2(function()
    {
        var x = 1;
    });
}

function method2(callback) {
    $.ajax({
        type: "GET",
        async: true,
        url: "/MyController/MyMethod",
        success: function (data) {
            var y = 6;
            callback();
        }
    });
}

Upvotes: 1

VoronoiPotato
VoronoiPotato

Reputation: 3183

If it's synchronous and if the GET is successful then Y is initialized first. If it's asynchronous it could be either, but I'd put my money on X simply because I'd suspect it'd go on before the web method returns. That being said there's no assurance that X will be fired first.

Upvotes: 2

Related Questions