3

I am trying to send out network data. Essentially, the library I am using has a 16kb limit on message size, so I must break down larger messages and send them in chunks. A really simplified version of my code might look like:

function sendInChunks(buffers) {
    send(buffers.shift()).then(sendInChunks.bind(undefined, buffers));
}

With a recursive implementation like this, the amount of data I can send is limited by the stack depth limits of whatever platform the code is running on. I was wondering if there is a way to send my data without the limitation of stack depth?

Note: In the actual implementation I have right now, I am actually using mutual recursion to do some checks after calling send. There is also some state from a higher scope used in both functions, but hopefully that wont change much.

EDIT: I am using es6 promises.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Paul
  • 849
  • 1
  • 7
  • 18
  • Can you clarify which implementation of ES6 Promises you are using? If this pattern is limited by stack depth, there is a bug. – Kris Kowal Feb 21 '14 at 17:33

2 Answers2

4

Promises are asynchronous, which means it's not actually recursive calls; it's more like a loop. A simple example of this is the following, which isn't recursive either.

function send(buffers){
    buffers.shift();
    if (buffers.length) {
        setTimeout(send.bind(null, buffers), 10);
    }
}

send(buffers);

When we call send, it shifts a buffer, and then maybe registers a timeout, and then returns. Because it returns without calling itself, it's not recursive.

side note: With ES6, there's proper tail call optimization; which means recursion limits won't be a problem as often.

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Excellent! Is this documented somewhere? – Paul Feb 20 '14 at 21:58
  • It's a combination of several things, as well as common promise implementations; the ES6 spec draft; and Promises/A+. I'd have to dig through all of them to find exact quotes. A little reading between the lines is also required. – Brigand Feb 25 '14 at 11:21
1

the amount of data I can send is limited by the stack depth limits of whatever platform the code is running on

No. Since Promises are resolved asynchronously, a new stack frame will be used for each callback, and you won't run into a stack overflow.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375