简体   繁体   中英

jQuery promises and dependent AJAX calls

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?

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]
  };
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM