3 ms·
I do not undetstand the async example. What is the difference between try { const response = await fetch(url); const text = await respons
by shp0ngle 9y ago
I do not undetstand the async example. What is the difference between
try {
const response = await fetch(url);
const text = await response.text();
element.textContent = text;
} catch (error) {
element.textContent = error.message;
} finally {
hideLoadingSpinner();
}
and
try {
const response = await fetch(url);
const text = await response.text();
element.textContent = text;
} catch (error) {
element.textContent = error.message;
}
hideLoadingSpinner();
?
Other than that, this is great. But I don't understand the async/await version
- olalonde 9y agoIf "element.textContent = error.message" throws an error, "hideLoadingSpinner()" won't get called (in the second example).
- deleted 9y ago[deleted]
- stefano 9y agoIf "element" is undefined or null, the catch clause will raise an exception. In the first example, hideLoadingSpinner() will be called anyway, while in the second one it won't.
- slackingoff2017 9y agoFinally blocks ensure code executes even on exception. In the second example hideLoadSpinner will never get called if you hit the catch block
- Rusky 9y agoThat's wrong- if the catch block runs without throwing any exceptions of its own then hideLoadSpinner will be called.
- GroSacASacs 9y agoincorrect try { throw new Error("catch me !"); // force try to fail } catch (catchedError) { console.log("inside catch"); // throw new Error("hmm"); } finally { // always executed console.log("inside finally"); } // always executed console.log("after try catch finally"); the finally statement can be useful when another error is thrown inside the catch block, in which case you have more serious problems in your code
- tantalor 9y agoIn this case, if the error object is undefined/null, then error.messsage throws a TypeError, and the spinner is not hidden. In general the finally { ... } block is useful because it is guaranteed to execute after the try/catch (if the program has not exited), where as the next line after the try/catch is not, e.g., the try/catch returns, or the catch block throws.
- hughes 9y agoIf that's what the example is showing, then it's just obscuring two unrelated try/catch blocks. One for the outcome of the request, and one for the uncertainty of the element reference.
- l1ambda 9y agoExample: (()=>{try {return 42} finally {console.log('you will see this')}})() The fn body returns 3, but also the "finally" executes first and you get the console.log. Same with: (()=>{try {throw 42} finally {console.log('you will see this')}})()
- deleted 9y ago[deleted]