Lucas
Lucas

Reputation: 3471

Jquery Deferred object issue when chaining .then

I'm having an issue with my returned data for the chained then being the 1st deferred data. The first example works:

api.getData().done(function(data){
  api.getData2().done(
    function(data2){
      $.log('success', data2);
    });
  });

But the second example SHOULD work, having data2 for the second .then(), but for some reason its the same as data1.

api.getData().then(function(data1){
  return api.getData2();
}).then(
function(data2){
  $.log('success', data2);
});

Any suggestions?

Upvotes: 2

Views: 873

Answers (2)

Lucas
Lucas

Reputation: 3471

So After some research JQuery Deferred.Pipe I found out I can't chain .then, but instead need to use pipe like below (.pipe() is chainable):

api.getData().pipe(function(data1){
  return api.getData2();
}).then(
function(data2){
  $.log('success', data2);
});

Upvotes: 1

adeneo
adeneo

Reputation: 318182

$.when will accept two asynchronous functions that returns a promise and execute the .then() function when both are done :

$.when( api.getData(), api.getData2() ).done(function(data, data2) {
    $.log('success', data2);
});

If for some reason (like needing the data) you need to perform getData() before getData2(), there really is no need for .then(), as your first example seems valid enough for that?

Upvotes: 1

Related Questions