jQuery promise with getJSON and callback

Guy Z picture Guy Z · Jan 5, 2013 · Viewed 21.6k times · Source

I have an ajax call with a callback. I want to call another method JUST after the callback has ended..I used the promise API from jQuery but as you can see below the second method is called before the first one has completed.

Any ideas?

  my.data = function () {
     var loadFlights = function (callback) {
        //$.getJSON("/api/Acceptance/", function (data) {
        //    callback(data);
        //}); 
        $.getJSON("/api/Acceptance").success(function (data) {
           console.log("first: " + new Date().getTime());
           callback(data); 
        })
        .then(console.log("second:" + new Date().getTime()));
     };

     return { load: loadFlights }
  }();

result to console:

second:1357393615115 
first: 1357393615246 

Answer

Blender picture Blender · Jan 5, 2013

Instead of providing a callback function to .then(), you're passing in the output of console.log("second:" + new Date().getTime()) (which is why second gets printed immediately).

Make an anonymous function that wraps the code that you want to call (just like you did in .success()):

$.getJSON("/echo/json").success(function(data) {
  console.log("first: " + new Date().getTime());
}).then(function() {
  console.log("second:" + new Date().getTime())
});

Demo: http://jsfiddle.net/Blender/fJb7h/