Deferred : done / then

Illustration of differences between

by LeGEC

HTML

<button id="first">First</button>
<button id="second">Second</button>
<div id="log"></div>

JavaScript

function makeDeferred() {
    var dfd = $.Deferred();
    dfd.done(function (res) {
        $('#log').append('<p>action resolved : ' + res + '</p>');
    }).fail(function (res) {
        $('#log').append('<p>action failed : ' + res + '</p>');
    });

    return dfd;
}

// "action" returns a deferred, which will be resolved after a
// 1 second timeout
function action(result) {
    var dfd = makeDeferred();
    setTimeout(function () {
        dfd.resolve(result);
    }, 1000);

    return dfd;
}

function failure(result){
    var dfd = makeDeferred();
    setTimeout(function () {
        dfd.reject(result);
    }, 1000);

    return dfd;
}

$('#first').click(first);
function first() {
    $('#log').empty().append('<h4>First example : chaining done callbacks</h4>');
    failure('first example').then(function(){}, function(){})
    .fail(function(msg){ alert(msg); });
}

$('#second').click(second);
function second() {
    $('#log').empty().append('<h4>Second example : chaining deferreds using then</h4>');
    action('second example').done(function () {
        $('#log').append('<i>You should see "then 1" appear in one second,  then "then 2" after another second. "then 2" receives the result produced by "then 1" - not the initial result</i>');
    }).then(function (res) {
        return action(res + ' then 1');
    }).then(function (res) {
        return action(res + ' then 2');
    }).done(function () {
        $('#log').append('<p><i>This message is logged after the last deferred resolves</i></p>');
    });
}