使用 Waterline ORM 时,如果我想使用默认提供的 bluebird Promise api,如何将处理传递回控制器。
下面是代码:
module.exports = {
//Authenticate
auth: function (req, res) {
user = req.allParams();
//Authenticate
User.authenticate(user, function (response) {
console.log(response);
if (response == true) {
res.send('Authenticated');
} else {
res.send('Failed');
}
});
}
};
module.exports = {
// Attributes
// Authenticate a user
authenticate: function (req, cb) {
User.findOne({
username: req.username
})
.then(function (user) {
var bcrypt = require('bcrypt');
// check for the password
bcrypt.compare(req.password, user.password, function (err, res) {
console.log(res);
if (res == true) {
cb(true);
} else {
cb(false);
}
});
})
.catch(function (e) {
console.log(e);
});
}
};
我只是想实现一个身份验证功能。业务逻辑很简单。我感到困惑的是请求流是如何交回给控制器的。如果我尝试返回响应,承诺不会响应,但执行 cb(value) 可以。
遵守承诺的关键是永远不要打破链条。承诺链取决于每一步返回一个承诺或一个价值,或者throwing一个错误。
以下是您的代码的重写。注意
- 路径中的每个回调都会返回一些内容,每个函数都会返回它所使用的承诺链(甚至
.auth()
;它可能在某些时候有用)
- 我用过蓝鸟的
.promisifyAll()
使bcrypt
一起玩
- 我已经脱钩了
.authenticate()
从您的请求/响应基础设施中,通过使username
and password
论点明确。这样可以更轻松地重复使用。
现在我们有了(没有 100% 测试,我没有费心安装水线):
module.exports = {
// authenticate the login request
auth: function (req, res) {
var params = req.allParams();
return User.authenticate(params.username, params.password)
.then(function () {
res.send('Authenticated');
})
.fail(function (reason) {
res.send('Failed (' + reason + ')');
});
}
};
and
var Promise = require("bluebird");
var bcrypt = Promise.promisifyAll(require('bcrypt'));
module.exports = {
// check a username/password combination
authenticate: function (username, password) {
return User.findOne({
username: username
})
.then(function (user) {
return bcrypt.compareAsync(password, user.password)
})
.catch(function (err) {
// catch any exception problem up to this point
console.log("Serious problem during authentication", err);
return false;
})
.then(function (result) {
// turn `false` into an actual error and
// send a less revealing error message to the client
if (result === true) {
return true;
} else {
throw new Error("username or password do not match");
}
});
}
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)