Promise To Use jQuery AJAX Correctly?

Callbacks are the cornerstone of JavaScript since it is single-threaded in nature. This can quickly turn into spaghetti code when handling multiple, dependent AJAX calls.

Enter Promises

Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like AJAX. So now instead of using callbacks like this:

    url: '/data/people.json',
    dataType: 'json',
    success: function (resp) {
    fail: function (err) {

Now you chain the responses using "done" and "fail" like this:

    url: '/data/people.json',
    dataType: 'json'
}).done(function (resp) {
}).fail(function (err) {

It really gets interesting when you want to wait for multiple AJAX calls, that's where $.when comes in:

    .done(function (resp1, resp2) {
        console.log(resp1); //data from people.json
        console.log(resp2); //data from products.json
        //cool eh?
    }).fail(function (err) {

You might be asking what's the point, nothing has changed except syntax. First of all, the callback method has been deprecated so that should suffice, but things become really elegant when you return AJAX calls:

function someRequest(data) {
    return $.get('/data/people.json', data);

Then those that consume the function can do this:


This way, you are abstracting the AJAX call in case you switch out jQuery or if it's not even an AJAX call at all... it's a promise!

Happy Coding!!
comments powered by Disqus

Get weekly updates in your inbox!