2

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"?

3
  • 3
    guaranteed - synchronous code always completes before asynchonous code can start Commented Jul 22, 2020 at 1:31
  • blog.bitsrc.io/…. is very useful in understanding how this all works. Commented Jul 22, 2020 at 1:47
  • 1
    Depends if what's hidden by the comments can change: jsfiddle.net/e6wvqb1p But if you are sure echoWorld is async, then yes, the order here is guaranteed. Commented Oct 27, 2020 at 2:53

2 Answers 2

1
+50

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

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

Comments

1

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.

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.