Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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/

like image 942
Lukasz R. Avatar asked Mar 20 '13 11:03

Lukasz R.


1 Answers

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

like image 52
Fabrício Matté Avatar answered Sep 20 '22 04:09

Fabrício Matté