by shp0ngle · 9y ago · 0 comments
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
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.
(()=>{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')}})()
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