Ali B
Ali B

Reputation: 1117

$.when vs Q.when behavior with Deferreds

I'm working with the Q.js library to do promises. I've tried the following scenario, where a function waits on another one to resolve a deferred before executing some code, and it works fine with jQuery native promises. However, the same code returns immediately with Q.js. Any ideas?

Fiddle: http://jsfiddle.net/ArN8F/5/


HTML:

<button id='go'>Go</button>
<p id='txt'></p>
<p id='txt2'></p>

jQuery code (waits 2 seconds then changes the text):

$(document).ready(function () {
    var dfd = $.Deferred();
    $('#go').click(function () {
        $('#txt').text('Clicked!');
        promised();
        setTimeout(dfd.resolve, 2000);
    });

    function promised() {
        $.when(dfd).done(function () {
            $('#txt2').text('Done');
        });
    }
})

Q.js code (changes text immediately):

$(document).ready(function () {
    var dfd = Q.defer();
    $('#go').click(function () {
        $('#txt').text('Clicked!');
        promised();
        setTimeout(dfd.resolve, 2000);
    });

    function promised() {
        Q.when(dfd, function () {
            $('#txt2').text('Done');
        });
    }
})

Upvotes: 1

Views: 817

Answers (1)

Tony
Tony

Reputation: 7445

I guess, you should use Q.when like this:

Q.when(dfd.promise, function () { 
     // .. 
});

Notice that it is dfd.promise, not just dfd.

Working demo.

Upvotes: 2

Related Questions