代码一致性
未来扩展性
错误处理
可读性
try {
// your code
} catch (err) {
console.error(err);
} finally {
console.log('done');
}
try {
const data = JSON.parse('{invalid json}');
} catch (err) {
console.error('解析失败:', err);
} finally {
console.log('done');
}
// 封装函数
async function getData() {
try {
const res = await fetch('https://glpla.github.io/utils/data/coffee.json');
const json = await res.json();
console.log(json);
} catch (err) {
console.error(err);
} finally {
console.log('done');
}
}
// 调用
getData();