简体   繁体   中英

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

I am trying to set up a note-taking app using Node and Express. Right now whatever note is saved overwrites what is in the db.json file. I am trying to push whatever is already in the db.json to an empty array, push the most recent note and then write the file using that final array. Does anybody have any tips on what I am doing wrong here? Thank you.

  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));
  }

Try this:

 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);
      })
  }

You don't need a then for simple synchronous actions like pushing an item into an array. You only need then for promises.

Without seeing the content of your writeFileAsync function I can't give you an exact answer but the issue is that you're most likely overwriting the file content instead of appending to it. check out this quick tutorial on how to write and append contents to a file

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM