Karan Kumar
Karan Kumar

Reputation: 3176

Getting Unhandled Promise Rejection Warning in NodeJS

I wonder why I am getting this err/warning even though my code looks okay.

Here's the UserModel I started building:

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

Please help, new to NodeJS world.

Upvotes: 1

Views: 870

Answers (1)

psehgal
psehgal

Reputation: 59

Like the comment says, you should put a try/catch around the await in getAll. Like this:

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

Upvotes: 1

Related Questions