繁体   English   中英

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

[英]function return pending promise instead of result

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

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) ,我会得到结果,但是当我调用该函数时,我会得到一个挂起的承诺而不是结果。

我错过了什么?

isAuthorized本身就是一个异步函数,并且总是会返回一个 Promise。 所以如果你调用isAuthorized ,必须等待结果被解析:

var auth = await isAuthorized()

或者

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

一旦代码的一部分以异步方式返回数据,所有其他依赖于它的东西也必须异步。 不管是Promise / async , callbacks , ..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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