0

I just started learning about jQuery Deferred, but I think I understood in theory. When trying to use them in a script, I have the feeling I am misusing them. Take this example:

var dataA = $.get('http://www.example.com');

dataA.done(function (result) {
    var dataB = $.get('http://www.example.com?name='+result.name);

    dataB.done(function(result) {
        console.log('Data fetch successful: ' + result)
    });
});

dataB depends on the outcome of dataA, so some kind of execution order has to be preserved. Am I using the done callbacks correct is this example?

To me it still feels like regular "callback hell" because I declare dataB inside dataA.done, so is suspect there is a more idiomatic way.

Sven
  • 12,997
  • 27
  • 90
  • 148
  • Using `done` is never really correct. You should always use `then`. – Bergi Apr 29 '16 at 14:37
  • @Bergi Really? I think if you're binding a simple done callback then you don't really need the deferred-piping abilities of `then` – Matt Diamond May 03 '16 at 18:33
  • @MattDiamond: You don't need it, but it doesn't hurt. It simplifies the code and makes maintaining easier in case you need chaining or use a different promise library, and it's easier to always use `then`, preventing mistakes such as this. And there only a few cases where you don't need chaining. – Bergi May 03 '16 at 20:12

0 Answers0