javascript - 为什么我在调用 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;
解决方案
它返回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
推荐阅读
- c++ - 读取一行并使用下一行信息c ++
- python - 如何在 Python 中使用多记录器
- python - Seaborn 图在一个月的开始和结束时显示两个标签
- javascript - 反应原生:有办法只在native-base lib的手风琴的3选项卡中定位图标吗?
- elasticsearch - 无法启动面临权限问题的logstash
- rust - 如何从 GTK Treeview 中清除或删除项目?
- c# - 无法使用空格作为分隔符拆分列表内容 - C#
- html - HTML && CSS 输入边框移动
- python - matplotlib tab10 调色板的十六进制代码是什么?
- jenkins - 从 GitLab 到 Jenkins 的 Webhook 返回 HTTP 404