-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.

Community
  • 1
  • 1
vitaly-t
  • 24,279
  • 15
  • 116
  • 138

1 Answers1

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.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • That's great, makes life much easier. Cheers! – vitaly-t Apr 05 '15 at 11:15
  • P.S. I don't care if down-voters remove my question, it was a very valid one, and I got a good answer. – vitaly-t Apr 05 '15 at 11:17
  • 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. – Peter Hansen Apr 22 '17 at 14:50
  • @PeterHansen In a properly implemented promise library [it should not](http://stackoverflow.com/a/29931657/1048572) – Bergi Apr 22 '17 at 14:59
  • @Bergi, granted, but that implies I would need to study the one(s) I'm using to verify they avoid that. Since I'm relying on native Promises at the moment, that seems a more than difficult task. – Peter Hansen Apr 23 '17 at 12:01
  • 1
    @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… – Bergi Apr 23 '17 at 12:05
  • @Bergi, thanks, I was afraid that might be the only answer. I can't easily test on every platform on which the code might run, so for now I'll just avoid doing that. – Peter Hansen Apr 23 '17 at 18:27