javascript - 在 NodeJS 中获得未处理的 Promise Rejection 警告
问题描述
我想知道为什么我得到这个错误/警告,即使我的代码看起来不错。
这是我开始构建的 UserModel:
const fs = require('fs');
class UserModel {
constructor(filename) {
if (!filename) {
throw new Error('Require a filename...');
}
this.file = filename;
try{
fs.accessSync(this.file); //to check if the file exists already
} catch (err) { //if not, make a new file
fs.writeFileSync(this.file, ['']);
}
}
async getAll() {
return JSON.parse(await fs.promises.readFile(this.file,{
encoding: 'utf8'
}));
}
}
//to test the above code
const test = async () => {
const user = new UserModel('users.json');
const data = await user.getAll();
console.log(data);
}
test();
请帮助,NodeJS 世界的新手。
解决方案
就像评论说的那样,你应该在in周围放一个try
/ 。像这样:catch
await
getAll
const fs = require('fs');
class UserModel {
constructor(filename) {
if (!filename) {
throw new Error('Require a filename...');
}
this.file = filename;
try{
fs.accessSync(this.file); //to check if the file exists already
} catch (err) { //if not, make a new file
fs.writeFileSync(this.file, ['']);
}
}
async getAll() {
return JSON.parse(await fs.promises.readFile(this.file,{
encoding: 'utf8'
}));
}
}
//to test the above code
const test = async () => {
const user = new UserModel('users.json');
try {
const data = await user.getAll();
console.log(data);
} catch (error) {
// handle error
console.log(error.stack)
}
}
test();
推荐阅读
- sql - 在任何位置将 - 替换为 0(零)
- python - 我怎样才能从结果中得到隐藏的副产品?
- html - powershell 在使用 IE 11 时是否有任何异常?为什么 getElementByID、标记名甚至 IHTML3 都不起作用?
- mongodb - 将插件安装到 Logstash 时出现 ELK 错误
- bash - 在 jupyter notebook 中执行 bash 脚本但得到错误 mkdir: command not found
- android - 我应该使用哪种方法来代替 setLatestInfo?
- javascript - Wordpress/PHP:在条件下显示不同的登陆页面
- node.js - 无法使用 http 模块在 Node.js 中传输文件
- inkscape - 如何手动设置节点手柄的角度和长度
- node.js - NodeJS Mongoose 更新文档