0

I have created a new promise function to set the asynchronous geolocation as a global function.

function getUsrLoc() {
return new Promise(function(resolve, reject) {
                    if(navigator.geolocation){
                        navigator.geolocation.getCurrentPosition(resolve)
                    } else {
                        reject('Geolocation is not supported by this browser or OS');
                    }
                });
}

Now I have created a function to push the coordinates to a new array whilst returning the new variable with the expected array items once I run the .then method.

//push coordinates into new array

function showPosition(position) {
     var coordinates = new Array();
     coordinates.push(Math.floor(position.coords.latitude))
     coordinates.push(Math.floor(position.coords.latitude))
     console.log(coordinates);
     return coordinates;
}

Now I can run the .then method on the getUsrLoc() function and plug in the showPosition function as a parameter.

getUsrLoc().then(showPosition);

Now on running, I the coordinates are printed to the console (after the browser prompt) but are not returning the new variable coordinates.

coordinates;
//undefined

What am I missing here?

S Roughton
  • 73
  • 5
  • Where are you printing it? Please include the relevant code. – 31piy Apr 28 '18 at 12:56
  • 1
    `coordinates` var is only declared inside `showPosition` function ... so, yeah, it's undefined outside it – Jaromanda X Apr 28 '18 at 12:59
  • I am just using the google chrome browser console. return coordinates; does not store the newly generated coordinates that are displayed in the console after running getUsrLoc().then(showPosition); – S Roughton Apr 28 '18 at 12:59
  • I see Jaromanda, should I declare it outside before? How can I return it outside to be used in a different function? – S Roughton Apr 28 '18 at 13:01
  • It perfectly works in my browser (FF) given that you enable your browser to have location access. Also another thing is, i guess your second push should be the longitude. After reading your question once more... OMG.. [Do you really try to return something from an async call](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call)? – Redu Apr 28 '18 at 14:54

1 Answers1

0

You cannot declare a variable beforehand and expect it to have the correct value. You should instead create a then handler to get access to coordinates variable:

getUsrLoc()
  .then(showPosition)
  .then(function(coordinates) {
    // Do your stuff here
  });
31piy
  • 23,323
  • 6
  • 47
  • 67