首页 > 解决方案 > 在 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 世界的新手。

标签: javascriptnode.jsexpresspromiseasync-await

解决方案


就像评论说的那样,你应该在in周围放一个try/ 。像这样:catchawaitgetAll

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();

推荐阅读