测验

finally 块的目的是什么?

主题
JavaScript
在GitHub上编辑

TL;DR

JavaScript 中的 finally 块用于在 trycatch 块之后执行代码,无论是否抛出或捕获了错误。它确保某些清理或最终确定代码无论如何都会运行。例如:

try {
// Code that may throw an error
} catch (error) {
// Code to handle the error
} finally {
// Code that will always run
}

finally 块的目的

确保清理

finally 块通常用于确保某些清理代码运行,无论是否发生错误。这对于关闭文件、释放资源或重置状态等任务很有用。

async function fetchData() {
try {
const response = await fetch(
'https://jsonplaceholder.typicode.com/posts/1',
);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
console.log('Fetched data:', data);
} catch (error) {
console.error('An error occurred:', error);
} finally {
console.log('Cleanup code runs here');
}
}
fetchData();
// Try creating a typo in the URL to see error handling.

保证执行

finally 块保证其中的代码将在 trycatch 块完成后执行。即使在 trycatch 块中遇到 return 语句,也是如此。

function exampleFunction() {
try {
return 'Try block';
} catch (error) {
return 'Catch block';
} finally {
console.log('Finally block');
}
}
console.log(exampleFunction()); // Output: 'Finally block' followed by 'Try block'

处理异步代码

处理异步代码时,finally 块可用于确保在 Promise 解决后采取某些操作,无论其结果如何。

fetch('https://jsonplaceholder.typicode.com/todos/1')
.then((response) => response.json())
.then((res) => console.log(res))
.catch((error) => console.error('Fetch error:', error))
.finally(() => console.log('Fetch attempt finished'));

延伸阅读

在GitHub上编辑