7

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/

Liam
  • 27,717
  • 28
  • 128
  • 190
Lukasz R.
  • 2,265
  • 1
  • 24
  • 22

2 Answers2

10

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

Fabrício Matté
  • 69,329
  • 26
  • 129
  • 166
1

Try using .done(...) instead of .then(...). There are examples right in the jQuery documentation.

http://api.jquery.com/jQuery.when/

Louis Ricci
  • 20,804
  • 5
  • 48
  • 62