Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

78
Vistas
Turning a callback function into promise

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);
    })
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar

0

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);
  })

about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda