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

I am trying to understand the when function and pending 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 this callback to be successful first:

 sucess get JSON ready! 

How can i do this?

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

+7
source share
2 answers

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

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

Must be:

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

Fiddle

+10
source

Try using .done (...) instead of .then (...). The jQuery documentation has examples.

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

+1
source

All Articles