簡體   English   中英

如何將數組從一個 function 傳遞到 class 中的另一個?

[英]How can I pass an array from one function to another in a class?

我正在嘗試使用 Node 和 Express 設置一個筆記應用程序。 現在,保存的任何注釋都會覆蓋 db.json 文件中的內容。 我正在嘗試將 db.json 中已有的任何內容推送到一個空數組,推送最新的注釋,然后使用該最終數組寫入文件。 有人對我在這里做錯了什么有任何提示嗎? 謝謝你。

  read() {
    return readFileAsync(path.join(__dirname, "db.json"), "utf8");
  }

  write(note) {
    return writeFileAsync(path.join(__dirname, "db.json"), JSON.stringify(note))
  }

  getNotes() {
    return this.read().then(notes => {
      var notesObject = JSON.parse(notes);
    });
  }

  addNote(note) {
    const newNoteArray = [];
    const { title, text } = note;
    if (!title || !text) {
      throw new Error("Note 'title' and 'text' cannot be blank");
    }
    const newNote = { title, text, id: uuidv1() };;
    return this.getNotes()
      .then(notes => {
        newNoteArray.push(notes);;
      })
      .then(newNoteArray.push(newNote))
      .then(this.write(newNoteArray));
  }

嘗試這個:

 addNote(note) {

    const { title, text } = note;
    if (!title || !text) {
      throw new Error("Note 'title' and 'text' cannot be blank");
    }
    const newNote = { title, text, id: uuidv1() };
    return this.getNotes()
      .then(notes => {
        notes.push(newNote);
        return this.write(notes);
      })
  }

對於簡單的同步操作,例如將項目推入數組,您不需要then then你只需要承諾。

在沒有看到您的writeFileAsync function 的內容的情況下,我無法給您一個確切的答案,但問題是您很可能會覆蓋文件內容而不是附加到它。 查看有關如何將 append 內容寫入文件的快速教程

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM