函数返回挂起的Promise而不是结果

时间:2018-08-23 07:53:19

标签: javascript node.js mongoose

我想使用此功能来检查用户是否有权访问资源:

const Authorisation = require('../models/Authorisation');

const isAuthorized = async (role, employee, objectId) => {
  const myAuth = await Authorisation.find({ employee: employee.id })
    .populate('auth')
    .then(auth => {
      return auth
        .filter(authItem => role.includes(authItem.auth.name))
        .filter(
          authItem =>
            authItem.organisationtype[0].item.toString() === objectId.toString()
        );
    })
    .catch(err => {
      return err;
    });

  return myAuth;
};
module.exports = isAuthorized;

如果在返回之前在函数内部使用console.log(myAuth),则会得到结果,但是,当我调用函数时,则会得到待处理的Promise,而不是结果。

我想念什么?

1 个答案:

答案 0 :(得分:2)

isAuthorized本身是一个异步函数,将始终返回Promise。因此,如果您致电isAuthorized,则必须等待结果解决:

var auth = await isAuthorized()

isAuthorized().then( auth => ... })

只要代码的一部分以异步方式返回数据,依赖它的其他所有内容也必须通过异步方式返回。无论是Promise / asynccallbacks,..

相关问题