如何正确获取从承诺返回的值?

我正在使用nodejs + Express作为我的后端服务。

我有一个authenHandler.js文件来帮助authentication与sequ​​elize:

module.exports = { isAuthenticated: function(data) { models.Users.find(data) .then(function(user) { if (user) { return true; } else { return false; } }); } } 

当我在app.js中使用这个辅助函数时:

 app.use(function(req, res, next) { // process to retrieve data var isAuthenticated = authProvider.isAuthenticated(data); console.log(isAuthenticated); if (isAuthenticated) { console.log("auth passed."); next(); } else { var err = new Error(authenticationException); err.status = 403; next(err); } } }) 

这总是进入else语句,因为isAuthenticated打印行总是返回undefined。 看起来,promise在if-else语句被调用后返回了值。

我不确定如何连接authenHandler.js和app.js. 什么是最好的办法呢?

改变它以回报承诺

 isAuthenticated: function(data) { return models.Users.find(data) .then(function(user) { if (user) { return true; } else { return false; } }); } 

然后消耗诺言

 authProvider.isAuthenticated(data) .then((result =>{ var isAuthenticated = result; console.log(isAuthenticated); if (isAuthenticated) { console.log("auth passed."); next(); } else { var err = new Error(authenticationException); err.status = 403; next(err); } })) 

你的app.js是错误的,isAuthenticated返回诺言不返回布尔

你需要像这样修改app.js

 app.use(function(req, res, next) { // process to retrieve data authProvider.isAuthenticated(data) .then(function(isAuthenticated) { if (isAuthenticated) { console.log("auth passed."); next(); } else { var err = new Error(authenticationException); err.status = 403; next(err); } }); } })