示例
try {
let items = JSON.parse(localStorage.getItem('items'))
if(items.length === 0){
throw new Exception()
}
// other code
fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
console.error(e)
fetch('http://localhost:9004/load-items').then(...)
}
我在if块内抛出异常,因为我需要编写与catch块内相似的代码
try {
let items = JSON.parse(localStorage.getItem('items'))
if(items.length === 0){
fetch('http://localhost:9004/load-items').then(...) // The same code
}
// other code
fetch('http://localhost:9004/merge-items').then(...)
}catch(e){
console.error(e)
fetch('http://localhost:9004/load-items').then(...) // The same code
}
答案 0 :(得分:0)
如果您仅询问是否可以,则问“否”,那不是很好。
您可以将异常视为您不希望看到的东西,但是您可以预测到。您期望在您的代码中,有时(在一开始?)您的本地存储项目可能为空。
所以,更好:
const loadItems = () => {
fetch('http://localhost:9004/load-items').then(...) // The same code
}
try {
let items = JSON.parse(localStorage.getItem('items'))
if (items.length === 0) {
loadItems();
}
// other code
fetch('http://localhost:9004/merge-items').then(...)
} catch (e) {
console.error(e)
loadItems();
}