【问题标题】:Getting Unhandled Promise Rejection Warning in NodeJS在 NodeJS 中获得未处理的 Promise Rejection 警告
【发布时间】:2020-08-30 03:41:26
【问题描述】:

我想知道为什么我得到这个错误/警告,即使我的代码看起来没问题。

这是我开始构建的 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 世界的新手。

【问题讨论】:

  • 使用test().catch(console.error),或在test函数中的getAll调用周围放置一个try/catch
  • 由于test() 函数而收到警告。

标签: javascript node.js express promise async-await


【解决方案1】:

就像评论说的那样,你应该在getAllawait 周围加上一个try/catch。像这样:

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

【讨论】:

  • 不,我的评论建议它应该放在围绕 getAll() 调用,而不是内部 getAll 函数
  • 你也去掉了json解析
  • 好电话。编辑了答案。这种方法也应该处理未处理的承诺拒绝警告。
  • @psehgal Bergi 建议将错误处理移到getAll() 之外的观点是关注点分离。 getAll() 方法不知道并且不应该知道应该如何处理错误,只有调用者知道,所以调用者应该处理错误。您还以这种方式重复错误处理,因为假设内部错误得到处理,getAll() 返回Promise<undefined>,而test 中的data 变为undefined,这会导致另一个错误,无穷无尽。
  • 啊,我明白你的意思了。是的,我同意这是一个更好的设计。我会更新我对 OP 的回答。
猜你喜欢
  • 2020-09-13
  • 2018-08-06
  • 2018-02-13
  • 2021-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-07
  • 2018-01-11
相关资源
最近更新 更多