G.One
G.One

Reputation: 209

Understanding difference between $.ajax() and $.ajax().then

I am having trouble understanding the following code:

var x = $.ajax({
    url : "sample_url",
    dataType : "json",
    data : {
        "invalidate_cache" : true
    }
});

Now, if I do

var y = x.then();

It returns the same function as x. Also what would have been different if x had been assigned the following way (Apart from "Hello 1" getting printed during ajax success return):

var x = $.ajax({
    url : "sample_url",
    dataType : "json",
    data : {
        "invalidate_cache" : true
    }
}).then(function(data){console.log("Hello 1")};

Upvotes: 1

Views: 351

Answers (1)

The_Black_Smurf
The_Black_Smurf

Reputation: 5269

Both ajax and then functions will return you a promise. I don't want to explain the whole promise mechanism but to answer the question, the difference between the first and the second x is that the first one will be execute right after the ajax call resolve while the second one will resolve after the function specified as parameter in the then function is executed (Note that the then function will be executed after the ajax call resolves... this is called chaining).

Upvotes: 3

Related Questions