【问题标题】:Why I am getting undefined after calling fetchNotes为什么我在调用 fetchNotes 后变得不确定
【发布时间】:2018-08-09 13:44:22
【问题描述】:

addNote 函数调用fetchNotes 后,它显示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;

【问题讨论】:

    标签: javascript node.js command


    【解决方案1】:

    它返回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

    【讨论】:

      【解决方案2】:

      return JSON.parse(notes)不会把这个值存储在fetchNotes里面,因为它是异步的,所以你以后及时获取文件的内容。

      要异步执行,您可以使用 async/await :

      const fetchNotes = () => {
          return new Promise((resolve, reject) => {
              fs.readFile('data.json', (err,notes) => resolve(JSON.parse(notes)));
          }) 
      }
      
      const addNote = async (title, body) => {
        // ...
        const notes = await fetchNotes();
        notes.push(note);
        saveNotes(notes);
        return note;
      }
      

      你也可以同步进行:

      const fetchNotes = () => JSON.parse( fs.readFileSync('data.json') );
      
      const notes = fetchNotes();
      

      【讨论】:

        猜你喜欢
        • 2022-09-23
        • 1970-01-01
        • 2019-04-15
        • 2022-10-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多