0
export default class Permissions {
    constructor(admin, userName) {
        this.admin = admin
        this.userName = userName
        if (userName.length > 0) {  
            return new Promise((resolve, reject) => {
                fetch(`../employees`, options)
                    .then(res => res.json())
                    .then(resText => {
                        let userdata = resText.employees.find((i) => i.username === this.userName)
                        this.userRole = userdata !== undefined ? userdata.role : ''
                    })
            }).catch(err => {
                console.log(err)
            })
        }
    }

    static hasAccess(admin, userInfo) {
        return (!admin || userInfo.userRole === 'manager' ||
            userInfo.tempAdmins.includes(userInfo.userName)) &&
            (userInfo.userName !== undefined && userInfo.userName.length > 0) && 
            (userInfo.userRole !== undefined && userInfo.userRole.length > 0)
        }
    
}

I have a class called Permissions that checks whether the user has permission to a certain page. To get the userRole, I fetch the user info and match the data in the database to get the role.

However, when I try to do something like

const permissions = new Permissions(true, 'username')
Permissions.hasAccess(true, permissions)

It gives me an undefined error. When I try to console.log the permissions, it gives me a Promise Pending status.

What is the right way to do it?

Dawn17
  • 7,825
  • 16
  • 57
  • 118
  • Don't put the `fetch` inside the constructor, put that in a `static` method that returns a promise for the data and can be `await`ed. From that data, initialise your `Permissions` instance with a synchronous and side-effect-free constructor, then call a `hasAccess` instance method. – Bergi Aug 10 '20 at 22:36
  • Also avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi Aug 10 '20 at 22:37

0 Answers0