Search code examples
javascriptasynchronouscallbackwait

Wait for callback in javascript


I'm trying to create a function that returns a object with information of a callback:

var geoloc;

var successful = function (position) {
    geoloc = {
        longitude: position.coords.longitude,
        latitude: position.coords.latitude
    };
};

var getLocation = function () {
    navigator.geolocation.getCurrentPosition(successful, function () {
        alert("fail");
    });

    return geoloc;
};

How can I do this? The function getLocation return null value before successful is executed.

Thanks!


Solution

  • 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);
    });