我在 node.js 中尝试做的同步版本(为便于阅读而简化):
var value = null;
var allValues = [];
do{
value = getValue(value); //load the next value
if(value) allValues.push(value);
}while(value);
console.log("Got all values:",allValues);
目标是遍历所有值,但是除非我传入当前值,否则 getValue 函数将简单地返回第一个值(导致无限循环)。
在 node.js 中,getValue() 函数是异步的,我希望它是异步的,但是如果我这样做:
var allValues = [];
function iterateGetValue(value){
if(value){
allValues.push(value);
getValue(value,iterateGetValue);
}else console.log("Got all values:",allValues);
}
getValue(null,iterateGetValue);
我担心 N 次迭代下降(getValue 可能会在结束之前触发数千次)我会遇到堆栈限制问题(我不正确吗?)。我研究了 Promises 和其他异步技巧,但在我看来,所有这些技巧都在继续推动堆栈(我不正确吗?)。
我的堆栈限制假设是不正确的,还是有一些我遗漏的明显方法可以做到这一点?
此外,我不能忙等待将异步 getValue 转换为同步 getValue,这违背了使用异步的全部目的。