只是好奇是否可以将 try/catch 转换为 if/else 以及语法会是什么样子。下面是我正在构建的用于保存和删除笔记的 express js 应用程序的一些代码。
// Retrieves notes from storage
getNotes() {
return this.read().then((notes) => {
let parsedNotes;
// Below parsedNotes will add the parsed individual note to the stored notes array
try {
parsedNotes = [].concat(JSON.parse(notes));
} catch (err) {
// Returns empty array if no new note is added
parsedNotes = [];
}
// Returns array
return parsedNotes;
});
}
// Adds note to array of notes
addNote(note) {
// Construction of note prior to save
const {
title,
text
} = note;
// Adds a ID to the new note
const newNote = {
title,
text,
id: uuidv4()
};
// Gets notes, adds new notes, then will update notes with new note
return this.getNotes()
.then((notes) => [...notes, newNote])
.then((updatedNotes) => this.write(updatedNotes))
.then(() => newNote);
}
我是编程新手,只是好奇它是否可能以及如何完成。谢谢!