使用水线 ORM 时,如果我想使用默认提供的 bluebird promise api,我该如何将处理过程传回 Controller 。
代码如下:
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);
});
}
};
我只是想实现一个身份验证功能。业务逻辑很简单。我感到困惑的是请求流是如何交还给 Controller 的。如果我尝试返回响应, promise 不会响应,但执行 cb(value) 会起作用。
最佳答案
使用 promise 的关键是永远不要破坏链条。 promise 链取决于每一步,要么返回一个 promise 或一个值,要么抛出一个错误。
以下是您的代码的重写。注意
- 路径中的每个回调都会返回一些东西,每个函数都会返回它所使用的 promise 链(甚至
.auth()
;它在某些时候可能会有用) - 我已经使用 BlueBird 的
.promisifyAll()
来制作bcrypt
一起玩 - 我通过使
username
和password
参数显式化,将.authenticate()
从您的请求/响应基础结构中分离出来。这样可以更轻松地重复使用它。
所以现在我们有(没有 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");
}
});
}
};
关于node.js - SailsJS 水线与 bluebird promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30659272/