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

108
Visualizações
Javascript Promise Callback (when it is called)

This is a stupid question but I'm having a hard time understanding how functions are first-class citizens in javascript and when callbacks are called.

const promise = new Promise((resolve,reject) => {
    const error = false
    if(!error) {
        resolve("Promise resolved")
    } else {
        reject("Promise is rejected")
    }

})
console.log(promise) //Promise { 'Promise resolved' }

For the code above why does the callback inside the promise (resolve, reject) => {} get called when I create a Promise? Is this something in the constructor of the Promise class? I cannot understand why it is being called immediately.

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

0

The promise executor function is called immediately by the promise constructor. That's how it works. The usual point of that executor function is to initiate your asynchronous operation and then later when that asynchronous operation completes, you call resolve() or reject().

Here's an example of putting the plain callback version of fs.readFile() in a promise wrapper:

function readFilePromise(filename, options) {
    return new Promise((resolve, reject) => {
        fs.readFile(filename, options, (err, data) => {
            if (err) {
                reject(err);
            } else {
                resolve(data);
            }
        })
    });
}

Usage:

 readFilePromise("myfile.txt").then(data => {
     console.log(data);
 }).catch(err => {
     console.log(err);
 });

Note: This is just an example for illustration here. Nodejs now already has promisified versions of fs.readFile called fs.promises.readfile, but this structure can be used when you need to manually promisify other more complicated things that don't have their own promise interface yet.


For a real world example of promisifying something more complicated see the mapConcurrent() function here or the rateLimitMap() function 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