Execution order with jQuery-AJAX

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
Marius
Posts: 106

Execution order with jQuery-AJAX

I have this code (ajax is async):

Code: Select all

function echoHello(){
  return $.ajax({
    //this will return "hello";
  });
}

function echoWorld(){
  return "world";
}

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

console.log(echoWorld());
Which outputs "world" and "hello" (in that order). But in the order I call the functions it should output "hello" and "world".
Whay is the response from the ajax function is outputed after, even it is called first?

Admin
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:

Code: Select all

setTimeout(_ => { console.log('hello'); }, 0);
console.log('world');
// output: world hello
'world' will run first as the async function runs after the current block even though the time is set to 0.

Similar Topics