0

I am writing a small Node.js command line utility. I am packaging it all in one file, and the structure kind of looks like this when simplified:

(async() => {
  await someAsyncFunction();
  /* 1 */

  // Iterate through collection and call async functions serially
  array.forEach(async (element) => {
    await anotherAsyncFunction(element);    
  });
})().catch(err => console.log);

Now if I throw an error at point 1, the error gets passed to the bottom catch alright. However I want to add error handling to anotherAsyncFunction and the for loop surrounding it.

I tried creating the following helper function:

async function asyncForEach(array, fn) {
  for (let i = 0; i < array.length; i+=1) {
    await fn(array[index], index, array);
  }
}

I then rewrote my original iteration code as follows:

try {
  await asyncForEach(array, async (element) => {
    await anotherAsyncFunction(element);
  });
} catch (err) {
  throw err;
}

While this does work, it seems incredibly verbose. Is there a better way to solve this problem?

Thanks.

Justin Chang
  • 194
  • 12
  • 2
    Why do you even bother adding another try/catch block only to re-throw the error and catch it in the outer catch block?? – Nelson Owalo Aug 16 '18 at 17:33
  • @PlatinumIndustries Ah you are correct. I thought I needed that. I removed it and it still works. Thanks. – Justin Chang Aug 16 '18 at 17:34
  • @PlatinumIndustries However, the original question still stands, is there a better way to handle errors for awaits inside of a forEach or is this the best way? – Justin Chang Aug 16 '18 at 17:34
  • 1
    I think it would be better to use one main catch block, unless you still want to continue execution even after an error occurs on one function in the loop – Nelson Owalo Aug 16 '18 at 17:34
  • 1
    that is the best way as far as I can tell. That is if you want the script to fail if a function in the for loop raises an error. But if by any chance you want it to continue execution after an error in the for loop, put a try/catch error block and let it fail silently – Nelson Owalo Aug 16 '18 at 17:40
  • Just write `for (const element of array) { await anotherAsyncFunction(element); }` and be done with it. No need to introduce helper functions. But if you insist, the call should at least be simplified to `await asyncForEach(array, anotherAsyncFunction);` – Bergi Aug 16 '18 at 19:26
  • "*Iterate through collection and call async functions serially*" - that's not what `.forEach` does anyway. Don't ever use `forEach`. – Bergi Aug 16 '18 at 19:27

0 Answers0