3 ms·
You need to wrap in try/catch if you want to handle the errors, which is the same for sync functions that throw to be fair. But most of async operations are som
by msoad 11y ago
You need to wrap in try/catch if you want to handle the errors, which is the same for sync functions that throw to be fair. But most of async operations are somehow expected to fail due to their nature (like network calls) and people usually want to have error handling scenarios. But for sync functions we usually let the error terminate the program because if a sync function throws in runtime it means something is wrong in my program, not in networking...
- nvivo 11y ago> You need to wrap in try/catch if you want to handle the errors. Of course, the same way you need to add a second callback to a promise handler if you want to handle errors. There is no difference, really. You're just changing the way you write the code. Also, you're not forced to choose "await or promises". You can use both as you see fit, in the same block: async () => { // make 2 requests in parallel var p1 = fetchSomething(); var p2 = fetchAnotherThing(); // wait for both of them to be done await Promise.all(p1, p2); // continue when they're both resolved // these "await" only get the values since the promises are resolved doSomethingWithTheValues(await p1, await p2); } > But for sync functions we usually let the error terminate the program because if a sync function throws in runtime it means something is wrong in my program, not in networking This is just the way you're choosing to see the problem. Promises can be used for anything, it's not tied to networking. I usually write promises that will be resolved when a modal window closes or when an application event happens. It's just a simpler way to write code. The way you use it is up to you. Also, async/await makes debugging a lot easier. The debugger can understand that the next expression after an "await" is supposed to be in the same function context. No more adding breakpoints to the callback function because only you know how the code is called at runtime. You debug async functions as normal functions.