我应该如何通过依赖于previous循环的价值异步函数循环? [英] How should I loop through asynchronous functions that rely on the previous loop's value?
问题描述
什么我试图在node.js中做的同步版本(简化了可读性):
VAR值= NULL;
变种allValues = [];
做{
值=的getValue(值); //加载下一个值
如果(值)allValues.push(值);
}而(值);
的console.log(你觉得所有的值:allValues);
我们的目标是通过所有的值进行迭代,但是除非我传递的当前值getValue函数将直接返回第一个值(导致无限循环)。
在node.js的中的getValue()函数是异步的,我希望它是异步的,但如果我这样做:
VAR allValues = [];
功能iterateGetValue(值){
如果(值){
allValues.push(值);
的getValue(值,iterateGetValue);
}其他的console.log(你觉得所有的值:allValues);
}
的getValue(NULL,iterateGetValue);
我担心n次迭代下降(可能的getValue击中年底前发射上千次)我会打一个堆栈限制的问题(我是不正确的?)。我看着承诺等异步的招数,但所有的人都在我看来,继续推栈(我是不正确的?)。
是我的堆栈限制的假设不正确,或者是有一些明显的方式来做到这一点,我失踪?
另外,我不忙,迫不及待地打开异步的getValue成同步的getValue,这违背了使用异步的整个目的。
我会打一个堆栈限制
块引用>没有,你不会的。如果他们真的是异步的,那么接下来调用
iteratGetValue
将在一个新的堆栈帧 - 原产于异步回调处理程序的顶层执行上下文。这对承诺是相同的 - 其中一些甚至的需要的是异步的。The synchronous version (simplified for readability) of what I'm trying to do in 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);
The goal being to iterate through all values, however unless I pass in the current value the getValue function will simply return the first value (causing an infinite loop).
In node.js the getValue() function is asynchronous, and I want it to be asynchronous, however if I do this:
var allValues = []; function iterateGetValue(value){ if(value){ allValues.push(value); getValue(value,iterateGetValue); }else console.log("Got all values:",allValues); } getValue(null,iterateGetValue);
I'm concerned that N iterations down (getValue could fire thousands of times before hitting the end) I'll hit a stack limit problem (am I incorrect?). I've looked into Promises and other async tricks but all of them appear to me to continue to push the stack (am I incorrect?).
Are my stack limit assumptions incorrect, or is there some obvious way to do this that I'm missing?
Also, I can't busy-wait to turn the async getValue into a synchronous getValue, that defeats the whole purpose of using asynchronous.
解决方案I'll hit a stack limit
No, you won't. If they're really asynchronous, then the next call to
iteratGetValue
will be in a new stack frame - originating in the top-level execution context of the async callback handler. It's the same for Promises - some of which are even required to be asynchronous.这篇关于我应该如何通过依赖于previous循环的价值异步函数循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!