Позволяет реорганизовать первый блог, назвав его обещаниеФункции . Оно может быть написано таким образом, чтобы оно всегда возвращало обещание.
const promiseFunction = function (req, res, next) {
// I am assuming it is a express middleware and res is passed as the function arguments.
return new Promise((resolve, reject) => {
console.log(email, password);
var isAuthenticated = false;
isAuthenticated = model.authenticate(email, password)
.then(function (result) {
//console.log(model.authenticate(email, password));
console.log("is Authenticated ?: ", isAuthenticated);
if (isAuthenticated) {
console.log(isAuthenticated);
console.log("Success!");
res.render('/home');
return resolve()
}
else {
console.log("ko");
res.redirect("/");
return resolve()
}
}).catch(function (error) {
console.log(error);
return reject(error)
});
});
}
Приведенный выше код всегда возвращает обещание.
Лучший подход будет
const promiseFunction = function (req, res, next) {
// I am assuming it is a express middleware and res is passed as the function arguments.
return model.authenticate(email, password)
.then(function ({ isAuthenticated }) {
//console.log(model.authenticate(email, password));
console.log("is Authenticated ?: ", isAuthenticated);
if (isAuthenticated) {
console.log(isAuthenticated);
console.log("Success!");
res.render('/home');
}
else {
console.log("ko");
res.redirect("/");
}
})
}
и функция аутентификации будет:
User.prototype.authenticate = function (email, password) {
connection = this.connection;
return new Promise(function (resolve, reject) {
connection.query('SELECT * FROM users WHERE email = ? AND Password = ? AND is_deleted = 0', [email, password], function (error, results, fields) {
if (error) {
console.log("error ocurred", error);
return reject(error);
}
else {
var newResponse = Object.assign({}, response, {isAuthenticated: true})
return resolve(newResponse);
}
});
});
};