SailsJS水线与蓝鸟承诺

当使用水线ORM时,如果我想要使用蓝鸟许诺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); }); } }; 

我只是试图实现一个身份validationfunction。 业务逻辑非常简单。 我感到困惑的是,请求stream是如何交给控制器的。 如果我尝试返回响应,但承诺不响应,但做一个cb(值)的作品。

与诺言合作的关键是永远不要打破链条。 一个承诺链取决于每一步都返回一个承诺或价值,或抛出一个错误。

以下是您的代码的重写。 注意

  • path中的每一个callback函数都会返回一些东西,每个函数都会返回它所处理的promise链(甚至是.auth() ;它在某个时候可能会有用)
  • 我已经使用BlueBird的.promisifyAll()使bcrypt一起玩
  • 我通过明确地使用usernamepassword参数来解耦你的请求/响应基础结构中的.authenticate() 。 这样它可以更容易地重用。

所以现在我们(没有100%的testing,我没有打扰安装吃水线):

 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 + ')'); }); } }; 

 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"); } }); } };