What is pseudo-recursion? [duplicate]

半城伤御伤魂 提交于 2019-12-25 04:22:50

问题


Given

let doAsynchronousStuff = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve("abcdefg"[Math.floor(Math.random() * 7)])
    }, Math.PI * 1 + Math.random())
  })
  .then(data => console.log(data))
  .then(doAsynchronousStuff)
}

why is .then(doAsynchronousStuff) considered "pseudo-recursion"?

What is the difference between "recursion" and "pseudo-recursion"?

Context:

this isn't "real" recursion, because the event loop gets to unwind the stack before the .then callback gets called – Alnitak


回答1:


The definition in my head for "recursive function" is that it is self-referential AND that the functional result depends upon the self referential invocation.

That means that the recursive invocation must be "synchronous". But that "synchronous" call need only be so relative to the invocation that depends on it, not relative to the system. In other words, the recursive function can run one call deeper on each turn of the run loop, and needn't build a deep stack, e.g.

// recursive but async
function factorial(x) {
    if (x === 0) { return 1; }
    return factorial(x-1).then(function(r) {
        return asyncMultiply(r, x);  // imagining that does r*x asynch
    });
}

Since something like this doesn't build the call stack the way we (me?) were classically taught, it wouldn't be crazy to qualify that as "pseudo".



来源:https://stackoverflow.com/questions/40390979/what-is-pseudo-recursion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!