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

97
Visualizações
Eventloop in JavaScript with promises

Until this day I thought I knew how the event loop in javascript works, but I've faced a really strange issue. Maybe it's not strange for you, then I'd appreciate it if you can explain it to me, so here the example of code:

Promise.resolve()
  .then(() => {
      Promise.resolve().then(() => {
          Promise.resolve().then(() => {
              Promise.resolve().then(() => {
                  console.log('first mega inner then')
              })

              console.log('first very inner then')
          })

          console.log('first inner then')
      })

      console.log('first then')
  })
  .then(() => {
      Promise.resolve().then(() => {
          Promise.resolve().then(() => {
              console.log('second very inner then')
          })

          console.log('second inner then')
      })

      console.log('second then')
  })

Why is the order of console.logs is:

  1. first then
  2. first inner then
  3. second then
  4. first very inner then
  5. second inner then
  6. first mega inner then
  7. second very inner then

I personally expected it to be:

  1. first then
  2. first inner then
  3. first very inner then
  4. first mega inner then
  5. second then
  6. second inner then
  7. second very inner then

But it's not the end... The most interesting thing for me is when I add queueMicrotask after the second "then"

some code here...
.then(() => {
    Promise.resolve().then(() => {
        Promise.resolve().then(() => {
            console.log('second very inner then')
        })

        console.log('second inner then')
    })

    console.log('second then')
})

queueMicrotask(() => console.log('microtask'))

IT EXECUTES AFTER THE FIRST "THEN", so the order now is:

  1. first then
  2. microtask
  3. first inner then
  4. second then
  5. first very inner then
  6. second inner then
  7. first mega inner then
  8. second very inner then

What is going on? I understand nothing. I think this is the last thing I don't understand in JS and I will be very grateful to you if you can explain why it works like that, I won't be able to sleep till I know this 😂

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

0

There may be a misunderstanding of how promise is used here. In promise chaining, the .then method is activated as soon as the promise resolves. If you want to delay the action of the second part of the chain, you need to specify when to resolve in a new promise. This example shows how that would work.

When you call Promise.resolve().then it calls the resolve method of the Promise class and makes the then method available immediately. Although you are not delaying the resolve when calling the resolve method immediately, it still takes some time to preform the resolve, so the following line of code will not be blocked.

Hopefull this provides some insight into the magic of Promise in js

(new Promise(resolve => {
  Promise.resolve().then(() => {
    Promise.resolve().then(() => {
      Promise.resolve().then(() => {
        console.log('first mega inner then')
        resolve();
      })
      console.log('first very inner then')
    })
    console.log('first inner then')
  })
  console.log('first then')
}))
.then(() => {
  Promise.resolve().then(() => {
    Promise.resolve().then(() => {
      console.log('second very inner then');;
    });
    console.log('second inner then');
  });
  console.log('second then');
});

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