简体   繁体   中英

How to get data inside a Promise Value in Javascript?

I'm trying to get the role of a User in my router.js file so that I can create Vue-Router Navigation Guards.

If the User's role is equal to candidate he can see all of the routes with this requiresAuthCandidate that I added to my candidate routes, in the meta field. I will then to the same thing for Employers. Right now, candidates can see employer's routes and employer's can see candidate's routes. This should not happen.

Bascially I want to do something like this.

router.beforeEach((to, from, next) =>{

    if (to.meta.requiresAuthCandidate) {
        if (auth.getProfile().role === 'candidate') {
            next({
               name: "home"
            });
        }
    } else {
        next();
    }

});

When I console.log(auth.getProfile()); I get a Promise and then inside a PromiseValue and then inside some data. The problem is if I try console logging the data like this console.log(auth.getProfile().data); I get undefined . Below is a screenshot of my data. Any idea why I can't access this data like normal?

在此处输入图像描述

Use async/await to get the promise resolved content

router.beforeEach(async (to, from, next) =>{

if (to.meta.requiresAuthCandidate) {
    const user = await auth.getProfile()
    if (user.role === 'candidate') {
        next({
           name: "home"
        });
    }
} else {
    next();
}

});

I don't know your base code but as much I know

  • your auth.getprofile() return promise

    you have to wait for a response then you can get data object to access your role element

    like: function async(){ const myuser= await auth.getProfile(); // introduced in ES2016(async await) myuser.role; }

When a function returns a promise, you can use the "await" keyword to wait for the result of the promise before proceeding.

router.beforeEach(async (to, from, next) =>{

    if (to.meta.requiresAuthCandidate) {
        // If auth.getProfile() returns a promise, you need to use await
        const profile = await auth.getProfile();

        if (profile.role === 'candidate') {
            next({
               name: "home"
            });
        }
    } else {
        next();
    }

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM