Page 1 of 1

Execution order with jQuery-AJAX

Posted: 02 Nov 2020, 08:15
by Marius
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?

Execution order with jQuery-AJAX

Posted: 02 Nov 2020, 09:35
by 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.