Deferred Ajax Calls

by john_s

HTML

<a href="#">1</a> 
<a href="#">3</a> 
<a href="#">4</a> 
<a href="#">5</a> 
<a href="#">7</a>

JavaScript

function getBookIds(titleId) {
    return $.ajax('/echo/json/', {
        type: 'post',
        data: {
        json: JSON.stringify({ titleId: titleId }),
            delay: 0.5
        },
        dataType: "json"
    });
}

$.when.apply($, $('a').map(function() {
    var $this = $(this),
        deferred = $.Deferred();

    // We set an on-click hander on the <a> element so when it is
    // clicked, it makes the ajax call.
    $this.one('click', function() {
        var titleId = $this.text();
        $this.replaceWith($('<span></span>').text(titleId));
        getBookIds(titleId).done(function(data) {
            console.log('Ajax call returned: ' + data.titleId);
            // When the ajax call returns, we resolve the Deferred.
            deferred.resolve(titleId);
        });
    });

    return deferred;
}).toArray()).then(function() {
    // This gets executed when all the Deferreds have been
    // resolved.
    console.log('all ajax calls have returned');
});