Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> I've mucked around a fair bit with JS's async and never felt like it got in the way.

When functions return more than one Promise, or when one chains async functions calls, it isn't really clear Errors from which functions are likely to break out and result in an unhandled exception (read also: https://archive.is/ULT7P).

For example, does trapAllErrs() below trap 'em all? Not really. Why? The answer involves understanding the microtask queue and its place in the event loop.

   // traps all errors from a1 and a2, or so we hope
   async function trapAllErrs() {
     try {
       const p = Promise.all([a1(), a2()])
       const results = await p
     } catch (err) {}
   }

   // sync code in a1 never throws
   async function a1() {
     // do something sync
     // ...
     // a3 and a4 may throw errs
     return Promise.any([a3(), a4()])
   }

   // sync code in a2 may throw
   async function a2() {
     // do something sync
     // ...
     // a5 never throws
     const x = await a5()
     // ...
     return ans
   }


I don't understand why this is complex? We know that Promise.all completes on the first error. That's literally the most basic knowledge of Promise.all (it either completes when all promises resolve, or rejects on the first error).

You only need to understand basic JS to know why this doesn't work. You don't need to know anything about the microtask queue or event loop.

Or am I missing something?


Would you do a .catch on the await p to fix that?


The solution to catch the errors for each function would be to catch errors from each promise individually (possibly within their functions, or within wrapper functions). This solution would also clearly state the intent. Performing concurrent tasks and only catching the errors at a higher level is a tricky thing to define behavior against; .Net/C# does it with the `AggregateException`, but even that comes with its own difficulties (which error comes from which promise? which came first? did one cause the other?).


Why not use Promise.allSettled...?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: