jQuery - Deferred - Test

by johnpapa

HTML

<div id="foo">hello</div>

CSS

#foo{ border:1px solid red; padding:10px; display:none }

JavaScript

function getData() {
    return $.get('/echo/json/').success(function() {
        console.log('Fires after the AJAX request succeeds');
    });
}

function showDiv() {
    return $.Deferred(function(dfd) {
        $('#foo').fadeIn(3000, dfd.resolve);
    }).promise();
}


var fadeOut = function() {
    return $.Deferred(function(dfd) {
        $('#foo').fadeOut(3000, dfd.resolve);
    }).promise();
}



$.when(getData()).pipe(showDiv).pipe(fadeOut).pipe(showDiv).done(function(ajaxResult) {
    console.log('Fires after BOTH showDiv() AND the AJAX request succeed!');

    // 'ajaxResult' is the server’s response
});