官术网_书友最值得收藏!

Working with fetchNotes

First up, let's do fetchNotes, which will need the following try-catch block.

I'll actually cut it out of addNote and paste it in the fetchNotes function, as shown here:

var fetchNotes = () => {
try{
var notesString = fs.readFileSync('notes-data.json');
notes = JSON.parse(notesString);
} catch (e) {

}
};

This alone is not enough, because currently we don't return anything from the function. What we want to do is to return the notes. This means that instead of saving the result from JSON.parse onto the notes variable, which we haven't defined, we'll simply return it to the calling function, as shown here:

var fetchNotes = () => {
try{
var notesString = fs.readFileSync('notes-data.json');
return JSON.parse(notesString);
} catch (e) {

}
};

So, if I call fetchNotes in the addNote function, shown as follows, I will get the notes array because of the return statement in the preceding code.

Now, if there are no notes, maybe there's no file at all; or there is a file, but the data isn't JSON, we can return an empty array. We'll add a return statement inside of catch, as shown in the following code block, because remember, catch runs if anything inside try fails:

var fetchNotes = () => {
try{
var notesString = fs.readFileSync('notes-data.json');
return JSON.parse(notesString);
} catch (e) {
return [];
}
};

Now, this lets us simplify addNote even further. We can remove the empty space and we can take the array that we set on the notes variable and remove it and instead call fetchNotes, as shown here:

var addNote = (title, body) => {
var notes = fetchNotes();
var note = {
title,
body
};

With this in place, we now have the exact same functionality we had before, but we have a reusable function, fetchNotes, which we can use in the addNote function to handle the other commands that our app will support.

Instead of copying code and having it in multiple places in your file, we've broken it into one place. If we ever want to change how this functionality works, whether we want to change the filename or some of the logic such as the try-catch block, we can change it once instead of having to change it in every function we have.

主站蜘蛛池模板: 卫辉市| 珠海市| 香格里拉县| 松溪县| 内乡县| 中西区| 桦川县| 沙洋县| 洛扎县| 林甸县| 汉川市| 湄潭县| 水富县| 湟源县| 太湖县| 黄龙县| 和硕县| 安国市| 和硕县| 内江市| 扶沟县| 仁寿县| 定日县| 红安县| 临沭县| 建昌县| 天峻县| 五台县| 都兰县| 潼南县| 洮南市| 循化| 泊头市| 武宁县| 泊头市| 沐川县| 庆云县| 宣化县| 芦溪县| 乃东县| 清水河县|