Norbert
Norbert

Reputation: 2771

Getting correct data when using multiple deferred ajax calls

I have a function that uses two ajax calls in order to get the proper information:

var getUsers = function() {
  return $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js", function(foo) {
    return $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js", function(bar) {
      return foo['age'] = bar.type;
    });
  });
}

And an outside function that calls the current function and only continues when the calls are finished.

getUsers().then(function(result) {
  // ...
});

Now the weird thing is that if I display the result, the 'age' will show up in the console, but if I try to access it using result['age'], it will return undefined.

Is there a proper way of handling multiple deferred calls?

Code

http://codepen.io/norbiu/pen/bNRQxL

Upvotes: 3

Views: 88

Answers (1)

JamesT
JamesT

Reputation: 3028

Edit Instead of using a separate deferred, you can chain the ones returned from getJSON() like this

var getUsers = function() {
  var foo;
  return $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js")
  .then(function(data) {
      foo = data;
      return $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js")
  }).then(function(bar) {
      foo['age'] = bar.type;
      return foo;
  });
}

Note: you need to save the return value from the first call or it won't be accessible to the second.

Original code for posterity

You can use a jQuery Deferred object and return that instead

var getUsers = function() {
  var dfd = $.Deferred();
  $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js")
  .done(function(foo) {
    $.getJSON("http://codepen.io/chriscoyier/pen/EAIJj.js")
    .done(function(bar) {
      foo['age'] = bar.type;
      dfd.resolve(foo);
    }).fail(function(e) {
       dfd.reject(e);
    })
  }).fail(function(e) {
      dfd.reject(e);
  });
  return dfd.promise();
}

http://codepen.io/anon/pen/pvwqZo

The deferred object won't resolve until both requests succeed (and will fail if any of them fail).

Upvotes: 2

Related Questions