【发布时间】:2023-03-15 00:39:01
【问题描述】:
所以我实际上是在使用 node.Js 编写一个简单的程序,但我在使用 async.waterfall 时遇到了问题:
-
我在我的用户模型中创建了一个通过访问数据库连接用户的函数,代码如下:
exports.connection = function (login,password) { async.waterfall([ function getLogin(callback){ usersModel.findOne({ login: login }, function (err, res) { if (err){ callback(err,null); return; } if(res != null ){ // test a matching password if the user is found we compare both passwords var userReceived = res.items[0].login; callback(null,userReceived); } }); }, function getPassword(userReceived, callback){ console.log(userReceived); callback(null,'done') } ], function(err){ if (err) { console.error(err); } console.log('success'); }); }使用节点检查器我发现主要问题(我认为)是当它进入瀑布函数时,它不执行 findOne 的回调函数,它实际上跳过了这个并直接跳转到 getPassword 函数(这是'也没有执行)。
因此,如果有人可以帮助我找出问题所在,那就太好了,因为我现在已经研究了大约两天。
谢谢
编辑: 添加不同的缺失测试案例后(这就是回调不起作用的原因)我有这个连接功能:
exports.connection = function (login,password) {
async.waterfall([
function getLogin(callback){
usersModel.findOne({ login: login }, function (err, res) {
console.log('login: ',res.login);
console.log('erreur: ',err);
if (err){
callback(err,null);
return;
}
if(!res)
{
console.log('getLogin - returned empty res');
callback('empty res');
}
if(res != null ){
// test a matching password if the user is found we compare both passwords
var userReceived = res;
callback(null,userReceived);
}
});
},
function getPassword(userReceived, callback){
console.log('login received :',userReceived.login);
var Ulogin = userReceived.login;
var Upassword = userReceived.password;
// function that compare the received password with the encrypted
//one
bcrypt.compare(password, Upassword, function(err, isMatch) {
if (err) {
console.log(err);
callback(err,null);
return;
}
else if (isMatch) {
console.log('Match', isMatch);
callback(null,isMatch);
}
else {
console.log('the password dont match', isMatch);
callback('pwd error',null);
}
});
},
], function(err){
if (err) {
console.error('unexpected error while connecting', err);
return false;
}
console.log('connected successfully');
return true;
});
}
在我的主文件 server.js 中,我目前正在做:
var connect = users.connection(login,password);
//the goal is to use the connect variable to know if the connection
//failed or not but it's 'undefined'
if(connect){
res.send('youyou connecté');
}
else {
res.send('youyou problem');
}
这绝对行不通,所以我尝试使用 Q 库,但我有一个错误提示
"TypeError: Cannot read property 'apply' of undefined at Promise.apply"
这是使用 Q 的代码:
app.post('/signup', function (req, res) {
var login = req.body.login;
var password = req.body.password;
Q.fcall(users.connection(login,password))
.then(function (connect) {
if(connect){
res.send('connected');
}
else {
res.send('problem');
}
})
.catch(function (error) {
throw error;
})
.done();
});
但我有点惊讶,我认为通过使用 async.waterfall() 我告诉函数等到它收到所有回调返回,所以我不明白为什么连接变量是“未定义”?
【问题讨论】:
-
您确定没有调用到
usersModel.findOne的回调吗?回调的编写方式,如果你最终遇到err是错误的并且res == null你永远不会调用异步回调的情况。 -
谢谢你,你是对的,但正如我在下面对 Gilad Bison 所说的,我的 server.js 文件中还有另一个问题。
标签: javascript node.js asynchronous mongoose