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"?
2
Answers
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
Hello will run first as the async function runs after the current block even though the time is set to 0.
$.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
And, for your information, as of jQuery 1.8, the use of async: false with jqXHR is deprecated.