-1

Is it possible to implement an asynchronous loop in JavaScript without recursion?

Case in point, is it possible to synchronize a queue of asynchronous tasks without resorting to recursion? We have N asynchronous tasks in a queue, and need to execute each task after the previous one has finished.

All the examples I've seen so far use recursion for this. But if we have to deal with a very long queue, we cannot expect anything good from a recursive approach. So what's the alternative then, how to tackle this?

Just so, when a similar question was asked about promises, every single answer relies on recursion.

2
  • can you give a concrete example? Commented Apr 5, 2015 at 10:46
  • The second paragraph is the concrete example. Commented Apr 5, 2015 at 10:46

1 Answer 1

3

we cannot expect anything good from a recursive approach.

Your premise is wrong. As you are doing it asynchronous, there is nothing wrong with a recursive approach (sometimes dubbed pseudo-recursion), it doesn't grow the call stack.

Sign up to request clarification or add additional context in comments.

7 Comments

That's great, makes life much easier. Cheers!
P.S. I don't care if down-voters remove my question, it was a very valid one, and I got a good answer.
It may not grow the call stack, but doesn't it steadily accumulate resources in an indefinitely long Promise chain? And if it does, there may be an unexpected delay when the chain is finally ended and all those resources are released. It may not be as bad as a stack overflow, but if true that's still quite sub-optimal.
@PeterHansen In a properly implemented promise library it should not
@PeterHansen I guess you could just try it out. Build an "infinite loop" promise, and profile the memory usage of your application. If it goes up, file a bug…
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.