Skip to content

Async forEach callbacks cause unpredictable results and prevent error handling #10156

@nicktrn

Description

@nicktrn

Issue Summary

Found many instances of forEach(async ..) pattern.

JS engine will just fire off the statements, go to the next line, and essentially run those async callbacks in the background.

It's impractical to handle or even catch errors with these constructs. It also creates race conditions that result in unexpected and unpredictable results.

This could be intentional, i.e. hackish way to implement "backround tasks" to speed up parent function returns. But I would strongly advise against this for the above reasons.

Steps to Reproduce

Example from wipemycal:

try {
  bookingRefsFiltered.forEach(async (bookingRef) => {
    // some code
  });
} catch (error) {
  // THIS WILL NEVER FIRE
  if (error instanceof Error) {
    logger.error(error.message);
  }
}
// THIS WILL RUN BEFORE THE ASYNC CODE
await sendRequestRescheduleEmail(..)

Actual Results

Parallel task execution, with:

  • uncaught errors + no error handling
  • unpredictable results

Expected Results

Parallel task execution, with:

  • error handling
  • predictable results

Evidence

forEach() expects a synchronous function

Metadata

Metadata

Labels

High priorityCreated by Linear-GitHub Sync🐛 bugSomething isn't working

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions