简体   繁体   English

Promise 中的递归

[英]Recursion in Promises

I am writing some software where one can execute a list of actions.我正在编写一些可以执行一系列操作的软件。 each of these actions basically is a Promise.这些动作中的每一个基本上都是 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.现在有可能,一个动作列表例如由 2 个项目组成,每个项目在完成最后一个项目后 0 秒执行,并启用循环,从而实际上生成一个无限循环。

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.因为在解释器返回空堆栈(即使它们立即解析)之前,promise 不会调用它们的.then()处理程序,所以这种类型的递归式编码风格不会建立堆栈 - 不管它递归了多少次。

So, this is safe, regardless of how many iterations it runs.所以,这是安全的,不管它运行多少次迭代。 It could even run indefinitely without any stack build-up.它甚至可以无限期地运行而没有任何堆栈堆积。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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