Skip to content Skip to sidebar Skip to footer

Async Javascript Callback

I can't seem to get my head around this problem. I'm using the Maxmind GeoIP2 JavaScript API with an async callback to return latitude, longitude and subdivision or region. <

Solution 1:

You just need to nest your synchronous stuff inside any async callback. The key to async programming is remembering that functions in JS are just objects and can be passed around.

So you define all your callbacks upfront, then chain them into one another. The below is by way of example (I assumed your database lookup was synchronous) so apologies if doesn't make perfect sense, but gives an idea on how to do the async bit.

Put everything inside the $(document.ready) rather than splitting it up into 2 scripts:

$(document).ready(function () {

    var weHaveFailed = function(){
        // do sad things
    };

    var getLocation = function(successCallback, failureCallback){
      geoip2.city(
        function (response) {
          // success!! Unpack the responsevar latitude = response.location.latitude;
          var longitude = response.location.longitude;
          var region = response.subdivisions[0].iso_code;

          // ... do other stuff// then callback the passed in successCallback function with your coordinates// and the function we want to execute when THAT is successfulsuccessCallback(latitude, longitude, region, updateTheLocations);                   
        },
        function (error) {
          // failure :(console.log(error.message);
          failureCallback();
        }
      );

    var lookup = function(lat, long, reg, successCallback){
      var locations = [];
      // ...get the data from the database, is this sync?// ...assign the response to our locations array// ... and call the passed in successCallback with the locations arraysuccessCallback(locations);
    };

    var updateTheLocations = function(locations){
      // We pass in the locations from the lookup call// do happy things, like synchronous JavaScript against the DOM
    };

    // start the ball rolling, passing in the function we want to run when geoip2 gets the datagetLocation(lookup, weHaveFailed);

});

Post a Comment for "Async Javascript Callback"