SailsJS 水线与蓝鸟承诺

SailsJS Waterline with Bluebird Promises

使用水线 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);
        });
    }
};

我只是想实现一个身份验证功能。业务逻辑很简单。我感到困惑的是请求流是如何交还给控制器的。如果我尝试 return 响应,承诺不会响应,但执行 cb(value) 会起作用。

使用承诺的关键是永远不要破坏链条。承诺链取决于每一步 返回 承诺或值,或 抛出 错误。

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

  • 路径中的每个回调 returns 东西和每个函数 returns 它使用的承诺链(甚至 .auth();它可能在某些时候有用)
  • 我用 BlueBird 的 .promisifyAll()bcrypt 一起玩
  • 我通过使 usernamepassword 参数显式化,将 .authenticate() 与您的 request/response 基础设施分离。这样可以更容易地重复使用它。

所以现在我们有(没有 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 + ')');
        });
    }
};

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