0

I'm trying to convert this code into promise (The one that i commented //). My goal is to print the user's location (longitude and latitude) but I'm having a hard time figuring it out, on how to convert this into Promise. (Sorry for my english)

// const getUserLocation = () => {
//     if (navigator.geolocation) {
//         navigator.geolocation.getCurrentPosition(succes, error);
//     } else {
//         console.log('Your browser does not support geolocation');
//     }
// }
// const succes = (positon) => {
//     console.log(positon.coords.latitude)
//     console.log(positon.coords.longitude)
// }
// const error = (err) => {
//     console.log('The User have denied the request for Geolocation.');
// }
// getUserLocation();

const getUserLocation = () => {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            resolve(navigator.geolocation.getCurrentPosition);
        } else {
             reject('The User have denied the request for Geolocation.');
        }
    })
}
getUserLocation()
    .then((response) => {
        console.log(response.coords.longitude);
        console.log(response.coords.latitude);
    })
    .catch((err) => {
        console.log(err);
    })
Mad
  • 1
  • 2
  • What's the problem? Your non-commented code is a promise already, right? – Bernhard Josephus Aug 11 '22 at 12:16
  • Looks like you want `navigator.geolocation.getCurrentPosition(resolve, reject)`. Right now, you're resolving with a reference to a function, not the result of a function. – Heretic Monkey Aug 11 '22 at 12:17
  • the error in my browser say's 'TypeError: can't access property "longitude", response.coords is undefined' – Mad Aug 11 '22 at 12:18
  • Side note: Looks like you're falling into the [explicit promise construction antipattern](https://stackoverflow.com/a/66747114/15299500), which isn't wrong, but it makes your code harder to read and manage. – samuei Aug 11 '22 at 13:33

3 Answers3

2

You are very close, the promise variant should look like this:

const getUserLocation = () => {
    return new Promise((resolve, reject) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(resolve, reject);
        } else {
            reject('The User have denied the request for Geolocation.');
        }
    })
}

In the code above you pass the resolve and reject functions to getCurrentPosition() which calls them with either the geolocation position, or an error (in the case of reject) as sole argument.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52
1

I'd just pass resolve and reject from the Promise function to the getCurrentPosition function.

const getUserLocation = () => {
  return new Promise((resolve, reject) => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(resolve, reject)
    } else {
      reject('The User have denied the request for Geolocation.');
    }
  })
}
getUserLocation()
  .then((response) => {
    console.log('success:', response.coords.longitude, response.coords.latitude);
  })
  .catch((err) => {
    console.log('error:', err);
  })
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
-1

No. That's not the way to do it. There is nothing special about promises. It is not a new syntax added to the language. It is just an ordinary constructor/class that you can write yourself in pure javascript. Therefore there is nothing special that resolve() can do to convert callbacks to promises.

The correct way is to pass the value passed to the callback to the resolve() function:

// To avoid confusion I rename the resolve() and reject() function to
// AAA and BBB. This is to illustrate that they are just variables
// **you** declare and do not have any special syntax. This is also
// to avoid confusion with the Promise.resolve() static method.

const getUserLocation = () => {
    return new Promise((AAA, BBB) => {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(succes, error);
        } else {
            console.log('Your browser does not support geolocation');
            BBB(new Error('Your browser does not support geolocation')); // optional
        }

        const succes = (positon) => {
            console.log(positon.coords.latitude)
            console.log(positon.coords.longitude)
            AAA(position); // This is how you correctly resolve()
        }
        const error = (err) => {
            console.log('The User have denied the request for Geolocation.');
            BBB(err); // This is how you correctly reject()
        }
    });
}

Basically you need to copy your success() and error() functions into the scope of your getUserLocation() function and then you MUST resolve or reject inside those functions.

slebetman
  • 109,858
  • 19
  • 140
  • 171