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

191
Vistas
How come the data runs from my promise without calling it

So I'm currently learning about promises in JavaScript, and I tried making my first promise and realized that it ran the setTimeout() even if I didn't call the promise to begin with, just by defining it, it ran by itself. This being postLogin.

const postLogin = new Promise((resolve, reject) => {
    setTimeout(() => {
        console.log("Token: 1234")
    }, 2000);
});

^ This logs out "Token: 1234" without calling postLogin.then()

Where as this doesn't run until I call postLogin1.then(token => {console.log(token)});

const postLogin1 = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Token1: 1234");
    }, 2000);
});

postLogin1.then(token => {console.log(token)});

Why is it that if I don't add "resolve" it runs the code without invoking it?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Promise constructors call the function you pass to them immediately. This is the case in both your examples.

If you have console.log inside that function, then it will call console.log. If you don't, then it won't. That's the key difference between the examples.

The then method just adds an event handler that will be called when the promise is resolved (or immediately if it has already been resolved).

If you have console.log in the then handler, then it will be called then the function resolves.

If you don't ever call resolve then it will never resolve. The function you pass to it is still called.

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