Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

491
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!