Matías Cánepa
Matías Cánepa

Reputation: 5974

execution order with jQuery's AJAX

I have this code (ajax is async):

function echoHello()
{
    return "hello";
}

function echoWorld()
{
    return $.ajax({
        //this will return "world";
    });
}

console.log(echoHello());

$.when(echoWorld()).done(function(response)
{
    console.log(response);
});

which outputs "hello" and "world" (in that order). But if change it a little bit, so the console.log() is in different order:

function echoHello()
{
    return "hello";
}

function echoWorld()
{
    return $.ajax({
        //this will return "world";
    });
}

$.when(echoWorld()).done(function(response)
{
    console.log(response);
});

console.log(echoHello());

is the same output guaranteed? Or it could potentially output "world" and then "hello"?

Upvotes: 2

Views: 148

Answers (2)

Chengmin
Chengmin

Reputation: 1895

$.ajax() returns a jqXHR Object which implements the Promise interface. And if async option is false, it sends a Synchronous Ajax Request and returns a resolved Promise.

And for the $.when() if the argument is neither Deferred nor Promise nor Thenable, it returns a resolved Promise.

So below example will print "Sync", "Hello", "World", "Async".

JSFiddle

jQuery(document).ready(function( $ ){
    let echoHello = () => "Hello";
    let echoAsync = () => $.ajax({url: "data:text,Async"});
    let echoSync = () => $.ajax({ async: false, url: "data:text,Sync" });

    let log = response => console.log(response);

    $.when(echoAsync()).done(log); // logs "Async"
    $.when(echoSync()).done(log); // logs "Sync"
    $.when(echoHello()).done(log); // logs "Hello"
    console.log('World'); // logs "World"
});

And, for your information, as of jQuery 1.8, the use of async: false with jqXHR is deprecated.

Upvotes: 1

Adrian Brand
Adrian Brand

Reputation: 21628

Ajax makes a call to the web server and is asynchronous. You don't know how long it will take. It is the same as

setTimeout(_ => { console.log('world'); }, 0);
console.log('Hello');

Hello will run first as the async function runs after the current block even though the time is set to 0.

Upvotes: 1

Related Questions