inverz inverz - 4 months ago 17
jQuery Question

jQuery deferred ajax execution order

I want to chain multiple functions one after another with promises, and each of the functions make an AJAX call.

something like this:



function myfunction1() {
console.log("myfunction1");
return $.ajax({
url: "/"
}).always(function() {
console.log("myfunction1 done");
});
}

function myfunction2() {
console.log("myfunction2");
return $.ajax({
url: "/"
}).always(function() {
console.log("myfunction2 done");
});
}


myfunction1()
.then(myfunction2());

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>





I would need
myfunction1
's callback to run before calling
myfunction2
.
So I would need this order:

myfunction1
myfunction1 done
myfunction2
myfunction2 done


but the code sample runs in this order:

myfunction1
myfunction2
myfunction1 done
myfunction2 done


Any help would be appreciated

Answer

Have you tried setting the ajax async to false?

function myfunction1() {
  console.log("myfunction1");
  return $.ajax({
    url: "/",
    async: false
  }).always(function() {
    console.log("myfunction1 done");
  });
}

http://api.jquery.com/jquery.ajax/

Edit: example using success callback

function myfunction1() {
  console.log("myfunction1");
  return $.ajax({
    url: "/",
    success: function() {
      console.log("myfunction1 done");
      myfunction2();
    }
  });
}

function myfunction2() {
  console.log("myfunction2");
  return $.ajax({
    url: "/"
  }).always(function() {
    console.log("myfunction2 done");
  });
}


myfunction1();