1

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")};
The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78
G.One
  • 209
  • 4
  • 15
  • `x` will always be promise returned by `$.ajax`. Promises can be chained using `then()`. Question is difficult to answer the way it is asked. Did you have different expectations for what `x` would be? – charlietfl Mar 09 '16 at 13:05
  • this is called chaining. see: http://stackoverflow.com/questions/1099628/how-does-basic-object-function-chaining-work-in-javascript – Hacketo Mar 09 '16 at 13:07
  • @charlietfl Yes. I expect different definitions for "x" when $.ajax() is assigned to it in comparison to $.ajax().then() I want to know the concept behind such declarations. – G.One Mar 09 '16 at 13:10
  • @Hacketo Thanks. I will look into this concept – G.One Mar 09 '16 at 13:11
  • Probably better to figure out what you are trying to do. – charlietfl Mar 09 '16 at 13:12
  • @charlietfl I am simply trying to assign an ajax promise to **x**. Later in the code, I will use x.then(function(y){ }); – G.One Mar 09 '16 at 13:14
  • And is it not working? If not then showing problematic code would be best rather than an abstract question of what `x` is – charlietfl Mar 09 '16 at 13:17
  • @charlietfl No, the code works. But I didn't know about chaining. I was under the assumption that $ajax and $ajax.then have different reference values – G.One Mar 09 '16 at 13:20
  • They would resolve differently if you returned something from `then()` – charlietfl Mar 09 '16 at 13:22
  • @charlietfl Sorry, I meant reference to function definition – G.One Mar 09 '16 at 13:23

1 Answers1

3

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).

The_Black_Smurf
  • 5,178
  • 14
  • 52
  • 78