Jason McDonough
Jason McDonough

Reputation: 147

JQuery when().done() not working properly

I need run some animation chain. I tried to use following code, but always second() was run at the same time as first()

example one:

var first = function(){
    var d = new $.Deferred();
    $('#ajax-contract-info').fadeOut(1400, function() {
                    $('#ajax-contract-info').removeClass('in');
                    $('#ajax-contract-info').css('display', '');
                    d.resolve();
            });
    return d.promise();
};

var second = function() {
    var d = new $.Deferred();
    $('#ajax-other-fields').fadeIn(1400, function() { d.resolve() });
    return d.promise();
};

$.when(first())
.done(second());

example two:

var first = function(){
    return $('#ajax-contract-info').fadeOut(1400, function() {
                    $('#ajax-contract-info').removeClass('in');
                    $('#ajax-contract-info').css('display', '');
            }).promise();
};

var second = function() {
    return $('#ajax-other-fields').fadeIn(1400, function() { d.resolve() }).promise();
};

$.when(first())
.done(second());

Where is a mistake?

P.S. I know, that I can use "complete" setting inside animation call, but I have a lot off animation with big condition list, using of "complete" setting will make code unreadable.

Upvotes: 2

Views: 583

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1074178

.done(second()) calls second and passes its return value into done, just like foo(bar()) calls bar and passes its result into foo. You just want to pass the function reference, so leave off the ():

$.when(first())
.done(second);
// No () ---^

You can also just use then on first(), no need for $.when unless you're combining parallel promises:

first().then(second);

And if you had a third, you could chain that onto the end, and it will wait for second to finish since second returns a promise:

first().then(second).then(third);

Upvotes: 5

Related Questions