Home > Software engineering >  Where will this callback function be registered in Node.js and how does it behave?
Where will this callback function be registered in Node.js and how does it behave?

Time:03-23

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?

CodePudding user response:

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)

CodePudding user response:

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!

  • Related