Wait for callback in javascript

44,503

Solution 1

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

Solution 2

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 object
var 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
    }); 
Share:
44,503
palvarez89
Author by

palvarez89

Systems and Embedded Software engineer. UNIX/Python/Shell, and many other things. Spent a few years building Linux Operating Systems and helping to develop Baserock. Sometimes I do Java/Android/Django/JS just for fun, so please, don't tell that to recruiters. "You see things and you say, 'Why?' But I dream things that never were and I say, Why not?"

Updated on July 09, 2022

Comments

  • palvarez89
    palvarez89 almost 2 years

    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!