Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

79
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda