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

500
Visualizações
Where will this callback function be registered in Node.js and how does it behave?
const add = (n1, n2, callback) => {
    setTimeout(() => {
        const sum = n1 + n2
        callback(sum)
    },2000)}

add(1, 4, (sum) => {
    console.log(sum) // Should print: 5
})

I know that the setTimeout function will be registered in the Node APIs stack and then in the callback queue after the time is done. my question is how will the call stack look like when 'add' function is called? given that it parses a new function. and how the call stack and callback queue will look like when 'callback' function is called?

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

0

for anyone who sees this question in the future i've figured it out. i used dev tools for node provided by Google chrome browser to see everything that was happening behind the scenes. it seems after the main() program is done and the timer is over, the callback function is called to the callback queue, and with it a 'closure' of the parent function that called it ('add' function), and that closure contains the arguments provided including the 'anonymous' arrow function. after the sum is calculated, the callback function is called and parses the data. which then the 'closure' pulls up the arrow function from the parent function and execute it using the data parsed from the callback.

i hope this helps anyone who had a similar question on their mind!

about 4 years ago · Juan Pablo Isaza Relatório

0

You can check for the callback stack easily by just

throw new Error()

in the passed function. When I do that, it seems to give:

Error
    at .../callback.js:10:8
    at Timeout._onTimeout (.../callback.js:4:3)
    at listOnTimeout (node:internal/timers:557:17)
    at processTimers (node:internal/timers:500:7)
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