Promise To Use jQuery AJAX Correctly?

By January 30, 2014 JavaScript No Comments

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!!

The following two tabs change content below.

Basem Emara

Software Architect at Falafel Software
Basem has over 10 years experience as a consultant and developer for dozens of projects for educational, advocacy, non-profit, small business, enterprise, and governmental organizations. As an innovator who recognizes and leverages the power of the web, he has been able to help real estate agencies, schools, hospitals, wholesale distributors, shipping carriers, and other businesses pioneer their industries utilizing the best that today’s technology has to offer from a more creative point of view. Simple yet elegant is the key to his approach, as well as the belief that continual process improvement is always possible.