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

105
Vistas
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 Respuestas
Responde la pregunta

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 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