Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery promise with getJSON and callback

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 
like image 929
Guy Z Avatar asked Jan 05 '13 13:01

Guy Z


People also ask

Is getJSON an Ajax call?

getJSON()) is an AJAX method that is used to fetch JSON data using HTTP GET request.

What is the difference between getJSON and Ajax in jQuery?

getJSON() is equal to $. ajax() with dataType set to "json", which means that if something different than JSON is returned, you end up with a parse error. So you were mostly right about the two being pretty much the same :).

How use jQuery deferred and Promise?

promise() will attach the methods onto it and then return this object rather than create a new one. This can be useful to attach the Promise behavior to an object that already exists. If you are creating a Deferred, keep a reference to the Deferred so that it can be resolved or rejected at some point.


2 Answers

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/

like image 74
Blender Avatar answered Oct 20 '22 20:10

Blender


Try with this:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
});

Reference: https://api.jquery.com/jquery.getjson/

like image 1
anayarojo Avatar answered Oct 20 '22 20:10

anayarojo