Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery ajax call inside a then function

So I need two ajax calls to get all the data. I am using jQuery's ajax call to achieve that. But then I am a bit confused at the execution order. Here is my problematic code:

$.ajax({
type: "GET",
url: "/api/data",
dataType: "json"
}).then(function (data) {
   console.log("I am the first")//correct
}).then(function () {
   //second ajax
    $.ajax({
    type: "GET",
    url: "/api/lifecyclephase",
    dataType: "json"
    }).then(function (data) {
       console.log("I am the second")//third
    })
 }).then(function () {
     console.log("I am the third")//second
 })

The output is

I am the first
I am the third
I am the second

Should not the thenwait for the second ajax to finish its job before proceeding?

The correct one:

$.ajax({
  type: "GET",
  url: "/api/data",
  dataType: "json"
}).then(function (data) {
  console.log("I am the first")
}).then(function () {
  $.ajax({
    type: "GET",
    url: "/api/lifecyclephase",
    dataType: "json"
  }).then(function () {
    console.log("I am the second")
  }).then(function(){
    console.log("I am the third")
  })
})
like image 385
Demi-Gods and Semi-Devils Avatar asked Jul 02 '26 04:07

Demi-Gods and Semi-Devils


2 Answers

In the problematic code, you are simply missing a return.

$.ajax({
    type: "GET",
    url: "/api/data",
    dataType: "json"
}).then(function (data) {
    console.log("I am the first");
}).then(function () {
    return $.ajax({
    ^^^^^^
        type: "GET",
        url: "/api/lifecyclephase",
        dataType: "json"
    }).then(function (data) {
        console.log("I am the second");
    });
}).then(function () {
    console.log("I am the third");
});

Without the return, there's nothing to inform the outer promise chain of the inner promise's exitence, hence the outer chain does not wait for the inner promise to settle before proceeding to the third stage.

like image 166
Roamer-1888 Avatar answered Jul 04 '26 16:07

Roamer-1888


The "second" $.ajax is initialized within the second .then, but that $.ajax isn't chained with anything else - the interpreter initializes the request and that's it, so when the end of the second .then is reached, the next .then (the third) executes immediately.

Try returning the second Promise instead - a subsequent .then will only wait for a Promise to resolve if that Promise is returned by the previous .then:

.then(function (data) {
   console.log("I am the first")//correct
})
.then(function () {
  //second ajax
  return $.ajax({
  // ...
like image 32
CertainPerformance Avatar answered Jul 04 '26 18:07

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!