Reputation: 2099
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?
Upvotes: 0
Views: 1187
Reputation: 665536
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]
};
});
Upvotes: 1