简体   繁体   中英

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 eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM