问题
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