当使用水平线ORM时,如果我想使用默认情况下提供的bluebird承诺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)是有效的。
发布于 2015-06-06 08:06:08
履行承诺的关键是永远不要打破锁链。承诺链取决于返回承诺或值或抛出错误的每一步。
下面是对代码的重写。请注意,
.auth();它在某个时候可能很有用).promisifyAll()让bcrypt一起玩.authenticate()和password参数显式化,我已经将username与您的请求/响应基础结构分离开来。这样,它可以更容易地重复使用。所以现在我们有(不是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");
}
});
}
};https://stackoverflow.com/questions/30659272
复制相似问题