I am thinking about JavaScript here, or any language that supports async IO or that sort of thing (coroutines? though don't have much experience with those).

I have looked at some of the resources below in trying to figure out how the stack works when you have async, but I don't understand it yet and don't quite follow some of the inner details of the posts.

Basically, when you have something like this, what happens?

setTimeout(() => {
  process() // takes a few milliseconds let's say
  setTimeout(() => process2(), 2)
  setTimeout(() => process3(), 1)
}, 2)
setTimeout(() => process4(), 2)

Does a new stack get created for each callback? You could have an example using async / await and Promises too, I think it would work the same.

By that I mean, not just a stack frame but a completely new stack? When the async callback comes back, a new stack is created. When that stack hits a new async function it just moves past it to the next function like normal. But wait, it has to keep track of the parent scope, so when the first function is "done" executing its synchronous stuff, its stack stays open in some ways because the callback needs access to its scope. How much of the stack remains? Then the callback executes, maybe calling another few nested async callbacks. Etc.

So what happens to the stack(s) exactly?

  • Is there more than one stack getting created? If so, when and where?
  • If so, how do the stacks get cleaned up generally speaking?

In my head there is some sort of tree structure being created asynchronously, but (a) I don't know if that's true, and (b) if it was true, I don't know what it would look like exactly or how it would function.


Since coroutines can be suspended without destroying the activation frame, we can no longer guarantee that activation frame lifetimes will be strictly nested. This means that activation frames cannot in general be allocated using a stack data-structure and so may need to be stored on the heap instead.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.