首页 > 解决方案 > 为什么我在调用 fetchNotes 后变得不确定

问题描述

fetchNotes从函数调用后,addNote它向我显示函数中undefined未定义push方法addNote

const fs = require('fs');
    const fetchNotes = ()=>{
      fs.readFile('data.json',(err,notes)=>{
        if(err){
         // return empty array if data.json not found
         return []; 
        }else{
         // return Object from data found data.json file
          return JSON.parse(notes)
        }
    });
    }


const saveNotes = (notes) =>{
  fs.writeFile('data.json',JSON.stringify(notes),()=>{
   console.log('Notes is successfully saved'); 
  });
}
const addNote = (title, body)=>{
  const note = {
    title,
    body
  }
  const notes = fetchNotes();
  //Push method not defined 
  notes.push(note);
  saveNotes(notes);
  return note;
}
module.exports.addNote = addNote;

标签: javascriptnode.jscommand

解决方案


它返回undefined是因为当您在回调中返回时,您并没有完全从fetchNotes函数本身返回。

也许您可以使用readFileSync并且不使用回调,或者您可以将其作为承诺并使用async/await

const fetchNotes = () => {
    return new Promise((res, rej) => {
        fs.readFile('data.json', (err, notes) => {
            if (err) {
                // return empty array if data.json not found
                res([]);
            } else {
                // return Object from data found data.json file
                res(JSON.parse(notes));
            }
        });
    });
}
const addNote = async (title, body) => {
    const note = {
        title,
        body
    }
    const notes = await fetchNotes();
    //Push method not defined 
    notes.push(note);
    saveNotes(notes);
    return note;
}

或者,您可以使用utils.promisify


推荐阅读