代码执行顺序

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.

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.

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();
        }
    });
}