[英]Why isn't the promise being passed on to the next then?
I am trying to determin whether the role of an admin in my app is a super user or not through this code:我试图通过以下代码确定我的应用程序中管理员的角色是否为超级用户:
AdminServices.js
管理服务.js
var isSuper_User = function(email) {
models.admin.findOne({ where: { email } }).then(function(admin) {
logger.debug("Fetching user with email: ", email);
logger.debug("admin.role: ", admin.role);
isSuper_User = admin.role === 'super_user' ? true : false;
logger.debug("isSuper_User: ", isSuper_User);
new Promise(function(resolve, reject) {
resolve(isSuper_User)
})
}).catch(err=>
logger.debug(err.toString())
);
};
admin_routes.js
admin_routes.js
router.get("/isSuperUser/:email", function(req, res) {
logger.debug("req.params.email: ", req.params.email);
adminService.isSuper_User(req.params.email).then(isSuper_User => {
logger.info("isSuper_User returned from promise: ", isSuper_User);
});
});
logger is a module that allows to customize the logging in the terminal. logger 是一个允许在终端中自定义日志记录的模块。
However when I send the request with an email, for a user whose role is an admin the logger code inside admin_routes doesn't log anything.但是,当我通过电子邮件发送请求时,对于角色是管理员的用户,admin_routes 中的记录器代码不会记录任何内容。 Everything inside AdminServices works perfectly though.
AdminServices 中的所有内容都可以完美运行。
This is what I get in the terminal :这是我在终端中得到的:
So the problem is with the way I handled the promise.所以问题在于我处理承诺的方式。 But, I do not see what I've done wrong exactly.
但是,我看不出我到底做错了什么。
Function isSuper_User
is not returning anything.函数
isSuper_User
没有返回任何东西。
Function should return the promise
函数应该返回
promise
var isSuper_User = function(email) {
return models.admin.findOne({ where: { email } }).then(function(admin) {
logger.debug("Fetching user with email: ", email);
logger.debug("admin.role: ", admin.role);
isSuper_User = admin.role === 'super_user';
//admin.role === 'super_user' already returns true or false so no need of ternary.
logger.debug("isSuper_User: ", isSuper_User);
return isSuper_User;
//No need of promise wrapper here.
}).catch(err=>
logger.debug(err.toString())
);
};
You have to return the promise from the function.您必须从函数返回承诺。 In the given code you are not returning anything, which is equal to
undefined
.在给定的代码中,您没有返回任何内容,这等于
undefined
。
var isSuper_User = function(email) {
return models.admin
.findOne({ where: { email } })
.then(function(admin) {
logger.debug("Fetching user with email: ", email);
logger.debug("admin.role: ", admin.role);
isSuper_User = admin.role === "super_user" ? true : false;
logger.debug("isSuper_User: ", isSuper_User);
return isSuper_User;
})
.catch(err => {
logger.debug(err.toString());
throw err;
});
};
The isSuper_User
function has no return
statement. isSuper_User
函数没有return
语句。
It doesn't return a promise, it returns undefined
.它不返回承诺,它返回
undefined
。
You need to explicitly return the promise.您需要明确返回承诺。
return models.admin.findOne....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.