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:
- First
foo()
is called.
- This then calls
asyncBar(foo)
.
- Because
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.
- That initial call to
foo()
returns and the stack is completely unwound. There is no foo()
on the stack any more.
- Any code after the call to
foo()
continues to run until it is done and returns back to the event loop.
- Meanwhile the asynchronous operation finishes some time in the future. That places a call to your callback in the event queue.
- When the JS engine is done executing other Javascript (which means the stack is completely empty), it pulls that event out of the event queue and calls the callback.
- In this case, the callback function is
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…