5

I have an async function that I want to call that waits on user action and resolves after some processing:

async function waitOnUserInput() {}

I want to wait on user input do some processing and repeat, so;

I want to implement this recursively like this:

async function actionUserStep() {
  await waitOnUserInput();
  actionUserStep();
}

Would this lead to a memory leak or a stack overflow of some sort? Or is this a bad way to model this kind of interaction?

1
  • How do you know when to stop? Recursive functions aren't "infinite" - they have to stop or you get a (wait for it) stackoverflow.....Or are you interested in streams? Commented Jun 3, 2020 at 21:14

2 Answers 2

3

No there will not be a stack overflow.

This is because the function returns once it processes the await expression.

The part after await is executed from the event loop, without any additional call stack, and when from there it makes the "recursive" call, it returns before making a deeper recursive call (because of the await). And so the call stack is empty again until the awaited promise resolves and things repeat as above...

Alternatively, you can also do this:

async function actionUserStep() {
    while (true) await waitOnUserInput();
}
Sign up to request clarification or add additional context in comments.

Comments

0

No, there will be no stack overflow, because async functions are handled using the JS event loop.

However, you will need to call the recursive function with await internally.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.