Tobi
Tobi

Reputation: 1313

Recursion in Promises

I am writing some software where one can execute a list of actions. each of these actions basically is a Promise. Each action might have a timer Trigger (where the next action is triggered when the timer ran down). Also, the list of actions might be loopable.

Now it might be possible, that a list of actions e.g. consists out of 2 items, each is executed 0 seconds after finishing the last one, and looping is enabled, thus actually generating an infinite loop.

This is no error in the application and thus be possible to do. My Code looks (extremely simplified) like this at the moment:

const actions = [...] // (() => Promise<void>)[]
const current = 0
const loop = true
const autoTrigger = true

const go() {
   if(current > actions.length && loop) current = 0
   current ++ 
   return Promise.resolve().then(() => {
      return actions[current - 1]()
   }).then(() => {
      if(autoTrigger) return go()
      return Promise.resolve()
   })
}

Is this code safe to run, assuming that it might not be aborted until it iterated a few hundred thousand times, or might it cause an error because the recursion gets too deep?

Upvotes: 1

Views: 117

Answers (1)

jfriend00
jfriend00

Reputation: 707158

Yes, it is safe to run. Because promises don't call their .then() handlers until after the interpreter has returned back to an empty stack (even if they resolve immediately), there is no stack build-up with this type of recursive-like coding style - no matter how many times it recurses.

So, this is safe, regardless of how many iterations it runs. It could even run indefinitely without any stack build-up.

Upvotes: 2

Related Questions