0

只是好奇是否可以将 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);
  }

我是编程新手,只是好奇它是否可能以及如何完成。谢谢!

4

1 回答 1

2

不是真的,不。if/else是合适的,例如,如果函数返回nullundefined出错。异常的行为与此不同:当抛出异常时,它会停止执行并跳转到catch与最近抛出异常的块相关联的try块。如果根本没有try阻塞,程序(通常)会崩溃。您不能使用if/检查异常,else因为它会跳出if包含它的块并直接转到该catch块或在没有try块的情况下使程序崩溃,而不执行其间的任何代码。

于 2021-09-08T02:03:43.080 回答