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.