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

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

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