如何在Java的Promise值内获取数据?

我试图在router.js文件中获得用户的角色,以便创建Vue-Router导航卫士。

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.

基本上我想做这样的事情。

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?

enter image description here

评论
烟花落
烟花落

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

});

点赞
评论
jculpa
jculpa

当一个函数返回一个promise时,您可以使用“ await”关键字来等待promise的结果,然后再继续。

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

});
点赞
评论