Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for callback in javascript

Tags:

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!

like image 695
palvarez89 Avatar asked Jul 31 '12 19:07

palvarez89


People also ask

How do you wait for callback function to finish?

JavaScript provides a setTimeout() method which can work with the callback function and the await keyword to wait for a function to finish. The objective of employing these methods is to execute a piece of code after waiting for a specific time.

How do you wait for promises to complete?

The keyword await is used to wait for a Promise. It can only be used inside an async function. This keyword makes JavaScript wait until that promise settles and returns its result. Here is an example with a promise that resolves in 2 seconds.


2 Answers

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);
});
like image 138
Rocket Hazmat Avatar answered Sep 20 '22 23:09

Rocket Hazmat


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
    }); 
like image 40
jbabey Avatar answered Sep 22 '22 23:09

jbabey