Deferred with jQuery - when() with getJSON() callbacks

Lukasz R. picture Lukasz R. · Mar 20, 2013 · Viewed 8.1k times · Source

I'm trying to understand when function and deferred objects in jQuery.

$.when($.getJSON('/echo/json', function () {
    console.log('sucess');
}, function () {
    console.log('error');
})).then(console.log('get JSON ready!'));

This example returns:

get JSON ready!
sucess

...but I want to achieve that success callback fires first:

sucess
get JSON ready!

How can I do that?

http://jsfiddle.net/lukaszr/rBFmL/

Answer

Fabrício Matté picture Fabrício Matté · Mar 20, 2013

You forgot the function wrapper - your code calls console.log immediately instead of passing a callback function:

.then(console.log('get JSON ready!'));

Should be:

.then(function() {
    console.log('get JSON ready!');
});

Fiddle