0

Take the following contrived example:

function foo(input) {
  if (typeof input !== 'string') {
    // An error is thrown synchronously here
    throw new Error('input must be string');
  }

  return new Promise(resolve => {
    // Do something async here and return the result
  });
}

Here, an error is thrown synchronously while the result of the computation is returned asynchronously. I know this can be easily overcome by rejecting with the error inside of the promise (or better yet, using an async function and throwing from inside of that), but does the above pattern introduce any strange behavior or is it considered an "antipattern" in any way?

jmartinezmaes
  • 359
  • 1
  • 8
  • `foo().catch(err => {})` will see strange behaviour - the error is caught depending on whether it is a synchronous exception or an asynchronous rejection. – Bergi Dec 31 '20 at 17:53
  • @j_maes54 - I've migrated [my answer](https://stackoverflow.com/a/65524149/157247) to the question Bergi quite correctly marked. Happy coding! – T.J. Crowder Dec 31 '20 at 18:01

0 Answers0