Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.when with deferreds not working

What I'm trying to do is make some action happen when two simultaneous image loads via ajax are done. To do this I created a custom Deferred to be resolved when the image loads are done.

<div id="i"></div>
$(document).ready(function() {
    $('#i').hide();
    var imgLoad = loadImgs();
    $.when(imgLoad).then(function() {
        $('#i').show('slow');
    });
});

function loadImgs() {
    var dfd = $.Deferred();

    var matrix = $.getJSON("https://graph.facebook.com/thematrixmovie");
    var pulp = $.getJSON("https://graph.facebook.com/pulpfiction");

    $.when(matrix, pulp).then(function(m, p) {
        mImg = '<img src=' + m[0].picture + '>';
        pImg = '<img src=' + p[0].picture + '>';
        $('#i').show().append(mImg + pImg);
        dfd.resolve;
    });
    return dfd.promise();
}

You can try this on JSFiddle.

I've used Eric Hynds post including a working example as a reference but still haven't gotten it to work. Any ideas?

like image 274
Soroush Hakami Avatar asked May 08 '26 14:05

Soroush Hakami


1 Answers

You're using $.when correctly, but you try to call the resolve method like this:

dfd.resolve;

Unlike some other languages, JavaScript doesn't allow you to omit the parentheses in a method call. You just need to add them and your code works correctly!

dfd.resolve();
like image 192
Jeremy Avatar answered May 11 '26 05:05

Jeremy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!