I have an asynchronous function that I want to call multiple times in a row. The problem is that "multiple" can be a few hundred thousand or millions...
The obvious way is to call the same function from the callback like that:
function foo()
{
asyncBar(foo);
}
Of course some logic is involved to stop the recursion. The question is whether the stack is filling with calls and may cause stackoverflow at some point?
The question is whether the stack is filling with calls and may cause stackoverflow at some point?
No. If asyncBar()
calls the callback it is passed asynchronously, then there is no stack build-up.
In your code:
function foo() {
asyncBar(foo);
}
here is what is happening, step-by-step:
foo()
is called.asyncBar(foo)
.asyncBar
is asynchronous, that means it starts an asynchronous operation (let's suppose it is an http GET, but any async operation will do). That asynchronous operation is initiated, but then asyncBar()
immediately returns.foo()
returns and the stack is completely unwound. There is no foo()
on the stack any more.foo()
continues to run until it is done and returns back to the event loop.foo
so it calls that function and starts the cycle all over again, right back to step 2.There is no stack build-up. The key is that asynchronous callbacks are called sometime later, after the current stack has finished, unwound and returned back to the system.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With