Async: eachSeries with a nested async call results in maximum call stack size exceeded

Created on 10 Aug 2016  ·  3Comments  ·  Source: caolan/async

What version of async are you using?

2.0.1

Which environment did the issue occur in (Node version/browser version)

Node 6.2.1
NPM 3.9.3

What did you do? Please include a minimal reproducable case illustrating issue.

let counter = 2000;

async.eachSeries(
  new Array(counter),
  (item, cb) => {
    async.parallel([
      (pCb) => {
        console.log(counter--);
        pCb();
      },
    ], cb);
  },
  () => console.log('done')
);

What did you expect to happen?

I expected each of the iterations to occur, which would result in the last two console.log's being '1' and 'done'.

What was the actual result?

After fewer than 1000 iterations, I would receive this error:

RangeError: Maximum call stack size exceeded

When I reverted back to async 1.5.2, the above code worked as expected.

question

Most helpful comment

The reason this worked in async 1.5.2 is we ensured the callback was always called asynchronously in that version. In version 2 we removed this guard (see https://github.com/caolan/async/blob/master/intro.md#synchronous-iteration-functions)

So in your case to fix the script you can either use async.ensureAsync(cb) or async.setImmediate(cb) to work around the recursion issue:

var counter = 2000;

async.eachSeries(
  new Array(counter),
  (item, cb) => {
    async.parallel([
      (pCb) => {
        console.log(counter--);
        async.setImmediate(pCb);
      },
    ], cb);
  },
  () => console.log('done')
);

All 3 comments

+1

+1

The reason this worked in async 1.5.2 is we ensured the callback was always called asynchronously in that version. In version 2 we removed this guard (see https://github.com/caolan/async/blob/master/intro.md#synchronous-iteration-functions)

So in your case to fix the script you can either use async.ensureAsync(cb) or async.setImmediate(cb) to work around the recursion issue:

var counter = 2000;

async.eachSeries(
  new Array(counter),
  (item, cb) => {
    async.parallel([
      (pCb) => {
        console.log(counter--);
        async.setImmediate(pCb);
      },
    ], cb);
  },
  () => console.log('done')
);
Was this page helpful?
0 / 5 - 0 ratings