Wait for callback in javascript Wait for callback in javascript javascript javascript

Wait for callback in javascript


Callbacks are used because the function is asynchronous. The callback runs at some point in the future.

So, yes getLocation returns before the callback is triggered. That's how asynchronous methods work.

You cannot wait for the callback, that's not how it works. You can add a callback to getLocation, that runs once it's done.

var getLocation = function(callback){    navigator.geolocation.getCurrentPosition(function(pos){        succesfull(pos);        typeof callback === 'function' && callback(geoloc);    }, function(){        alert("fail");    });};

Now instead of doing var x = getLocation() and expecting a return value, you call it like this:

getLocation(function(pos){    console.log(pos.longitude, pos.latitude);});


I would recommend the approach in Rocket's answer. However, if you really wanted to, you could trigger the rest of your code when the getLocation finishes by using a jQuery deferred object. This will give you more fine-grained control than just using the callbacks provided by getCurrentPosition.

// create a new deferred objectvar deferred = $.Deferred();var success = function (position) {    // resolve the deferred with your object as the data    deferred.resolve({        longitude: position.coords.longitude,        latitude: position.coords.latitude    });};var fail = function () {    // reject the deferred with an error message    deferred.reject('failed!');};var getLocation = function () {    navigator.geolocation.getCurrentPosition(success, fail);     return deferred.promise(); // return a promise};// then you would use it like this:getLocation().then(    function (location) {         // success, location is the object you passed to resolve    },     function (errorMessage) {         // fail, errorMessage is the string you passed to reject    });