0

I'd like to know how to make dependent AJAX calls using promises/deferred from jQuery. Right now I have something like this:

$.when($.ajax('https://somedomain.com/getuserinfo/results.jsonp', {
  dataType      : 'jsonp',
  jsonp         : true,
  jsonpCallback : 'userCallback'
}))
.then(function (data) {
  return $.when($.getJSON('http://www.otherdomain.com/user/' + data.userId), $.getJSON('http://www.anotherdomain/user').then(function (json1, json2) {
    return {
      json1  : json1,
      json2  : json2
    };
  });
});

It's working for me as expected, but I don't know whether it is a correct way of doing this. Do you have any suggestions on how to improve that?

sunpietro
  • 2,059
  • 4
  • 24
  • 42
  • 1
    You should move this to Code Review. http://codereview.stackexchange.com/ – David East Mar 08 '14 at 18:58
  • Well, my question is whether is that a correct way of doing such things? – sunpietro Mar 08 '14 at 19:02
  • 1
    You haven't explained why exactly you want to achieve, so we cannot really provide a better way for whatever it is you want to do. You can use `$.ajax(...).then(...)` intead of `$.when($.ajax(...)).then(...)`, but that's all there is to say now. – Felix Kling Mar 08 '14 at 19:11

1 Answers1

1

Well, your code already seems to work "correct", though there are a few things to improve:

$.when($.ajax(…))

You don't need $.when here, $.ajax already does return a promise.

$.when($.getJSON(…), $.getJSON(…).then(…)

You're missing a closing parenthesis somewhere here - probably before the .then. Assuming that:

….then(function(…){ return ….then(function(…){…}); })

Since promises are monadic, you can unnest these callbacks to

…
.then(function(…){ return …; })
.then(function(…){…})

to avoid the pyramid of doom.


jQuery-specific:

$.when(…).then(function (json1, json2) {
  return {
    json1: json1,
    json2: json2
  };
});

The arguments to the callback after a $.when are not the plain results, but the arguments objects of each getJSON deferred resolution. You probably only want the JSON, which is on the first index:

$.when(…).then(function (json1, json2) {
  return {
    json1: json1[0],
    json2: json2[0]
  };
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Well, thanks. But it's not the answer to my question. My question is how to make dependent AJAX calls. I mean I get user details from the first source (in $.when) and according to the data I got from it I'm making two AJAX calls simultaneously to two different sources and sending user details from the first source as params for another AJAX calls. – sunpietro Mar 08 '14 at 19:52
  • 1
    That's what I answered in the first sentence: It's done just like you did it! – Bergi Mar 08 '14 at 20:23
  • Thanks, I just thought it might be incorrect in some way. – sunpietro Mar 08 '14 at 20:50