3

I am wondering about some redundant functionality in jQuery and hope someone could shed some light into it.

jQuery.getJSON() takes as third argument a callback function for the successful completion of the request, but at the same time getJSON() also returns a jqXHR object which also comes with three callback functions (always(), done() and fail()).

Now my question is whether there is any semantical difference between passing the desired function as third parameter or as argument to done() (also in terms of best practices), respectively if there are any advantages or disadvantages in using either. As for the latter, the only disadvantage I could imagine (even though rather unlikely as scenario) is a timing issue in case the request is processed faster than the done() call can bind the passed function.

  • The argument is a callback function, while jQuery ajax methods returns a deferred, which again has certain methods. – adeneo Apr 19 '14 at 14:23
  • 4
    It's a backwards-compatibility thing. The "Promise" behavior is relatively new. They introduced it and of course opted not to break the Internet by removing the old callback version. – Pointy Apr 19 '14 at 14:23
  • @Pointy So there is practically no difference? What about my timing concern? – user3551867 Apr 19 '14 at 14:30
  • 1
    The Promise mechanism takes care of that. If the request has completed when you call `.done()` then your callback is invoked immediately. – Pointy Apr 19 '14 at 14:40
  • Thanks @Pointy, I just ran a quick test and discovered this behaviour. I guess I should read more about Promises. But about the topic, so I'd assume new code should rather use the respective functions instead of passing the function as argument, correct? – user3551867 Apr 19 '14 at 14:58
  • Well the new APIs really are more convenient, once you get used to them. – Pointy Apr 19 '14 at 15:21

0 Answers0