DEV Community

Discussion on: Is this async function recursive?

Collapse
peerreynders profile image
peerreynders • Edited on

It isn't a recursive function as it isn't calling itself (or being called via mutual recursion); the syntax sugar only makes it look that way.

Roughly:

function stuff() {
  return new Promise<void>(executor);

  // ---
  function executor(resolve: () => void, _reject: (reason?: Error) => void): void {
    // `someAsyncOperation()` is on the callstack
    // but `finish()` is only placed on the
    // microtask queue once
    // `someAsyncOperation()` resolves
    // When `finish()` starts the 
    // callstack is (practically) empty
    //
    someAsyncOperation().then(finish);

    // ---
    function finish() {
      stuff();
      resolve();
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

By the time you hit the .then() in executor() stuff() is done. The finish() portion is scheduled in a microtask, not called.

You could however argue that stuff() is recursively scheduled.