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

195
Visualizações
How to convert a callback function to a promise?

I have a simple callback function, created for my own learning use, which displays an alert once the first alert is displayed.

  <script>
    const sayMessage = (callbackFn) => {
    alert("Hello there customer!");
    callbackFn();
}

    sayMessage(() => {
      alert("You are about to enter Jims Gym supplies! Enjoy!");
})
    </script>

Now I wish to do the same but using a promise. This is what I've done so far before I got stuck.

<script>
  const promiseMessage = callbackFn =>{
    return new Promise((resolve, reject) =>{
      
    } )
  }
</script>

I have looked at other similar questions posted, however none have helped me in understanding how to convert using the example I have created.

I have looked at this question How do I convert an existing callback API to promises? and it does not help me understand.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

There are basically two types of functional arguments in javascript, which unfortunately often mixed up in the literature, hence the confusion.

The first type are actual callbacks, when you tell the engine to do some background job for you and literally call you back once it's ready. Examples are numerous APIs like fs.readFile, geolocation.getCurrentPosition etc etc. These can (and should) be converted to promises using the following pattern:

    someBackgroundJob(callbackFn)

becomes

    someBackgroundJobPromised => new Promise((resolve, reject) => {
        someBackgroundJob(() => {
            resolve or reject
        })
    })

The second type are function arguments that you see in functions like Array.map or RegExp.replace. These are not "callbacks" in the strict sense, just functions that are called in-order. It doesn't make sense to "promisify" these.

Your code is the second case, therefore no promises are needed here.

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