Javascript 函数返回挂起的承诺,而不是结果
我想使用此功能检查用户是否有权访问ressource:Javascript 函数返回挂起的承诺,而不是结果,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,我想使用此功能检查用户是否有权访问ressource: const Authorisation = require('../models/Authorisation'); const isAuthorized = async (role, employee, objectId) => { const myAuth = await Authorisation.find({ employee: employee.id }) .populate('auth') .then(
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)
,我会得到结果,但是当我调用函数时,我会得到一个挂起的承诺,而不是结果
我错过了什么?
已授权
本身就是一个异步函数,将始终返回一个承诺。因此,如果调用的已授权
,则必须等待结果得到解决:
var auth = await isAuthorized()
或
一旦代码的一部分以异步方式返回数据,依赖它的所有其他内容也必须以异步方式返回。无论是承诺
/异步
,回调
isAuthorized().then( auth => ... })