Skip to content Skip to sidebar Skip to footer

What Is The Difference In Following Pattern To Call Recursive Javascript Function Which Returns A Promise?

In following code with 100000 records recursiveFnReturnsPromiseV1 executes fine while recursiveFnReturnsPromiseV2 fails with out of stack exception. The only difference between two

Solution 1:

Lets strip away the Promise constructor antipattern, and use a simple Promise.resolve instead. Your functions now become

functionrecursiveFnReturnsPromiseV1(pValues, ix) {
  if (pValues.length <= ix)
    returnPromise.resolve();

  let p = document.createElement('div');
  p.innerText = ix + 'v1' + Date.now();
  document.getElementById('v1').appendChild(p);

  returnPromise.resolve().then(function() {
    returnrecursiveFnReturnsPromiseV1(pValues, ++ix);
  })
}

functionrecursiveFnReturnsPromiseV2(pValues, ix) {
  if (pValues.length <= ix)
    returnPromise.resolve();

  let p = document.createElement('div');
  p.innerText = ix + 'v2' + Date.now();
  document.getElementById('v2').appendChild(p);

  returnPromise.resolve(recursiveFnReturnsPromiseV2(pValues, ++ix));
}

It should be obvious by now why the second function overflows the stack.

Why doesn't the first as well? Because the recursive call is inside an asynchronousthen callback, which means it starts later (after the outer call returned) with a fresh call stack.

Post a Comment for "What Is The Difference In Following Pattern To Call Recursive Javascript Function Which Returns A Promise?"