0

I use a forEach loop in traverse

   await traverse(json).forEach(async function (value) {
       for(var i=0 i<10; i++)={
           var result=  await someFunction(i);
           var result2= doSomething(result);
       }
       var r = result2;
   }    

as soon as I set the inner function to async I get an Maximum call stack size exceeded error. What can I do?

daniel
  • 34,281
  • 39
  • 104
  • 158
  • 2
    It sounds like `someFunction` calls this code block, ie it indirectly calls itself and you have an endless cycle . Therefore at some point the call stack is too big – A_A Aug 27 '21 at 08:46
  • 3
    BTW `forEach` won't wait for `someFunction()` to get resolved. – Adil Bimzagh Aug 27 '21 at 08:48
  • 3
    None of the methods `traverse` offers understand `Promise`s or cares about them. – Andreas Aug 27 '21 at 08:49
  • 2
    We can't help without more information (what does `someFunction` do, for instance?). But using `async` functions as `forEach` callbacks is an antipattern if you don't A) want them to run in paralle, and B) use `try`/`catch` to handle rejections (since `forEach` doesn't do anything with the promise). More: https://stackoverflow.com/questions/37576685/using-async-await-with-a-foreach-loop – T.J. Crowder Aug 27 '21 at 08:50
  • I added some info, I have to await a result, therefore I need to use await? – daniel Aug 27 '21 at 11:56

1 Answers1

1

as @T.J. Crowder say

forEach doesn't care about async usage (doesn't wait for it). You can take a look at traverse-async.

I think this package can be more flexible for this scenario.

let queue = traverse(object, function(node, next) {
  someAsyncOperation(node)
  .then(next)
  .catch(err =>{
    queue.break();
  });
}, function() {
  console.log('Done!');
});
giveerr
  • 119
  • 4