jQuery Deffereds Tutorial

by HYEONGJINKIM

HTML

<div id="main">
    <div id="container"></div>
</div>

CSS

#container {
    width: 100px;
    height: 100px;
    background: #CCC;
}

JavaScript

var container = {
    initialize: function ($el) {
        // Store a reference to our element
        // on the page
        this.$el = $el;
    },
    fadeOut: function () {
        // Create a new Deferred.
        var dfd = new $.Deferred();

        this.$el.animate({
            opacity: 0
        }, 2000, function () {
            // When we're done animating
            // we'll resolve our Deferred.
            // This will call any done() callbacks
            // attached to either our Deferred or
            // one of its promises.
            //resolve reject 상관없이 먼저 오는게 있으면 그걸로 끝...
            dfd.resolve("Resolved fading out!");
            //dfd.reject("Rejected fading out!");
        });

        // Return an immutable promise object.
        // Clients can listen for its done or fail
        // callbacks but they can't resolve it themselves
        return dfd.promise();
    }
};

$(function () {

    // Hook the container object up to the #container div
    container.initialize($('#container'));

    // Instruct the container to fade out. When we call
    // fadeOut we should get a promise back as a return value
    var promise = container.fadeOut();

    // Now that we have a promise we can hook a done callback
    // onto it. The done() method will fire once the promise
    // is resolved.
    promise.done(function (message) {
        console.log(message);        
    });
    
    promise.fail(function (message) {
        console.log(message);
    });
    
    promise.always(function() {
        console.log('finish!!');
    });
});