Darren G
Darren G

Reputation: 868

.then() trying to run before promise resolved

I am writing a React application and am trying to write a function that returns the user's current location so that I can use it in my application. However, I am new to promises and my code is not working despite my best efforts. The code is below:

const getCurrentLocation = () => {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition((position) => {
      let currentCoordinates = {
        lat: position.coords.latitude,
        lng: position.coords.longitude
      }
      return Promise.resolve(currentCoordinates)
    })
  } else {
    return Promise.reject(new Error('Get User Location error'))
  }
} 

getCurrentLocation()
  .then((userCoords) => { console.log(userCoords) })
  .catch((error) => { console.log(error) })

I am receiving the error: "Unhandled Rejection (TypeError): Cannot read property 'then' of undefined" at the "getCurrentLocation()" line. Which I believe means .then() is trying to execute before getCurrentLocation() has resolved.

currentCoordinates is populating correctly, but after the error has been thrown.

As I'm new to promises I'm sure I'm doing something very simple wrong!

Upvotes: 0

Views: 87

Answers (2)

dotconnor
dotconnor

Reputation: 1786

navigator.geolocation.getCurrentPosition is a async method that requires a callback, so it will return undefined and the return method inside your callback is actually doing nothing.

Instead, you need to wrap your entire function in a Promise and resolve/reject from inside it.

const getCurrentLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition((position) => {
        let currentCoordinates = {
          lat: position.coords.latitude,
          lng: position.coords.longitude
        }
        resolve(currentCoordinates)
      })
    } else {
      reject(new Error('Get User Location error'))
    }
  })
}
getCurrentLocation()
  .then((userCoords) => { console.log(userCoords) })
  .catch((error) => { console.log(error) })

Upvotes: 0

Mark
Mark

Reputation: 92440

You can't use Promsise.resolve() like this because you are returning a value to the callback, not the original caller. You need to wrap the call in a promise and return that promise. When you have the result, the call resolve. Something like:

const getCurrentLocation = () => { 
    return new Promise((resolve, reject) =>{
        if (!navigator.geolocation) reject(new Error('Get User Location error'))
        else {
            navigator.geolocation.getCurrentPosition((position) => {
                let currentCoordinates = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude
                }
                resolve(currentCoordinates)
              })
        }

    })
  } 
  

Upvotes: 2

Related Questions