4 ms·
To be fair, all browsers are still missing ES6 features and all of them have newer stuff being implemented. As for the try catch, you don't NEED to wrap. The s
by nvivo 11y ago
To be fair, all browsers are still missing ES6 features and all of them have newer stuff being implemented.
As for the try catch, you don't NEED to wrap. The sample just shows you can. You can't do:
try {
promise.then(() => ...);
} catch {}
but you can do
try {
await promise;
...
} catch {}
async/await is a way to write simpler code the same way you would use a "for" block instead of a "while(iterator.next())" - because it's easier, all the rest is still the same.
- msoad 11y agoYou 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.
- notNow 11y agowhile(!iterator.next().done) I think you meant the above example and not the one you listed in the comment as generator objects in JS always return objects upon calling next method even after finish yielding for long and thus you could have an infinite loop on your hand here.