When processing a list in a loop that runs asynchronously and returns a promise, exiting processing on exception is not desired. Instead, the errors are aggregated and passed to the resolve callback in an outer finally block. I am curious if this approach is considered an anti-pattern and would appreciate guidance on the correct way to handle this situation. Thank you.
Here is an example:
async doSomething(list) {
let errorCount = 0
let errors = []
return new Promise(async (resolve, reject) => {
try {
list.forEach(async (item) => {
try {
actionThatThrows(item)
} catch (e) {
errorCount++
errors[errorCount] = e
}
})
} catch (e) {
errorCount++
errors[errorCount] = e
} finally {
if (errorCount > 0) {
resolve(errors)
} else {
resolve()
}
}
})
}