Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Event related recursion on Node.js

Lets say we have a function called doSomething();

Inside this function I am declaring an object called dispatcher.

dispatcher has a function that works asynchronously and omits an 'end' event when its finished.

So the code looks like this:

const doSomething = () => {
    const dispatcher = someObject.function.thatReturnsDispatcher();
}

So this doSomething() function is not totally useless and actually does so much more than just assigning a single variable and I want this dispatcher to do the same stuff that doSomething() does whenever its asynchronous function ends. So I do something like this:

const doSomething = async () => {
    //important stuff above

    const dispatcher = someObject.function.thatReturnsDispatcher();
    dispatcher.on('end' , () => {
        doSomething();
    });

    //important stuff below
}

and it works!

But I wonder one thing:

When it is called, does the function doSomething() works recursively or does the function end and node saves the discpatcher.on('end') function and calls it whenever an end event omits?

like image 257
boraarslan Avatar asked Aug 28 '26 05:08

boraarslan


1 Answers

Actually both.

There is no doubt that doSomething is recursively called (the next call to doSomething happens from within the current doSomething call).

And, depending on what are you doing in the commented out stuff, doSomething will probably end before the dispatcher callback gets called, dispatcher.on registers the callback to be called when the thing ends no matter whether doSomething ends or not.

like image 143
ibrahim mahrir Avatar answered Aug 30 '26 20:08

ibrahim mahrir



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!