我是Node.js的新手,当我运行代码Promise时总是在待处理状态。
错误
is Authenticated ?: Promise { pending }
承诺{待处理}
我尝试了其他方法来使用等待,但是我找不到正确的方法。感谢帮助。
代码
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');
} else {
console.log("ko");
res.redirect("/");
}
}).catch(function(error) {
console.log(error);
});
});
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);
reject(error);
return false;
} else {
resolve(results);
return true;
}
});
});
};
答案 0 :(得分:0)
让我们重构第一个博客,将其命名为 promiseFunction 。可以通过以下方式编写它,以便它始终返回承诺。
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)
});
});
}
上面的代码将始终返回promise。 更好的方法将是
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);
}
});
});
};