0

I am having trouble getting the geolocation coordinates returned from a promise function. I am using the code below which from here: How geolocation.getCurrentPosition return value?

const getPosition = () => {
  return new Promise((res, rej) => {
      navigator.geolocation.getCurrentPosition(res, rej)
  });
}

export const getGeolocation = () => {
  getPosition().then(console.log)
}

I tried:

export const getGeolocation = () => {
  return getPosition().then(result => return result)
} // doesnt work

Can someone explained to me what is the correct way to get values out of a promise? Thanks

Kayee
  • 168
  • 9
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call). Maybe better: https://stackoverflow.com/questions/29516390/how-to-access-the-value-of-a-promise – ggorlen Jan 23 '20 at 03:42

2 Answers2

1

You need to use Callback methodology instead return in getGeolocation() function.

Here is your solution :

export const getGeolocation = (callback) => {
  getPosition().then((result) => {
     callback(result);
  })
}

Now see the below code to access that result coming from the getPosition() function.

getGeolocation((result)=>{
   console.log("Position : ",result);
});

Please check this below code hope this should work for you and


const getPosition = () => {
    return new Promise((res, rej) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(res);
        } else {
            rej("Unable to found current location");
        }

    });
}

export const getGeolocation = (callback) => {
    getPosition().then((result) => {
        callback({
            code: 1,
            message: "Location",
            location: result
        });
    }).catch((_error) => {
        callback({
            code: 0,
            message: _error
        });
    });
}

getGeolocation((response) => {
    if (response.code == "1") {
        console.log(response.location);
    } else {
        console.log(response.message);
    }
});

To learn how callback work please go through the below link you will have a better idea.

https://www.w3schools.com/jquery/jquery_callback.asp

Bhargav Tailor
  • 442
  • 4
  • 8
0

Try this.

const getPosition = () => {
    return new Promise((res, rej) => {
        navigator.geolocation.getCurrentPosition(res, rej)
    });
}
const getGeolocation = async() => {
    try {
        let result = navigator.permissions.query({
            name: 'geolocation'
        });
        if (result.state == 'granted') {
            let respnse = await getPosition();
        } else {
            throw new Error("User denied Geolocation");
        }
    } catch (error) {
        console.log(error.message);
    }
}
getGeolocation();
Sohail Ashraf
  • 10,078
  • 2
  • 26
  • 42