所以我其實沃金與node.js的一個簡單的程序,我使用有一個問題async.waterfall:異步watefall不會調用函數
我在用戶模式創造出了功能通過訪問數據庫連接的用戶,這裏是代碼:
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');
}
這絕對不行,所以我試過使用問答庫,但我有一個錯誤說
「類型錯誤:無法讀取屬性未定義在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()我告訴函數等待,直到它收到所有回調返回,所以我不明白爲什麼connect變量是'undefined'?
你確定回調'usersModel.findOne'不叫?回調寫入的方式,如果您最終遇到'err'爲false且'res == null'的情況,那麼您永遠不會調用異步的回調函數。 – andyk
謝謝,你是對的,但正如我對吉拉德·比鬆經濟高速公路所說的, 我在我的server.js文件中有另一個問題。 – Zowak