簡體   English   中英

在 NodeJS 中獲取未處理的 Promise 拒絕警告

[英]Getting Unhandled Promise Rejection Warning in NodeJS

我想知道為什么我得到這個錯誤/警告,即使我的代碼看起來不錯。

這是我開始構建的 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 世界的新手。

就像評論說的那樣,你應該在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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM