How should I loop through asynchronous functions t

2019-02-26 02:03发布

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.

1条回答
Rolldiameter
2楼-- · 2019-02-26 02:14

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.

查看更多
登录 后发表回答