我在Node中使用'user-management'包,并且在回调中的回调中有回调。但最终的结果并没有回归。这是我的主要NodeJS模块:
playerManagement.login(data.username, data.pw, function (result) {
console.log(result) <-- statement never reached
if (result == "fail") {
socket.emit('client', { type: 'login', result : 'fail'});
} else {
connections[playerindex++] = {'username' : username, 'sockid' : socket.id, 'token' : result };
socket.emit('client', { type: 'login', result : 'success', username : username });
console.log(connections);
}
});
然后我有一个带有功能的外部模块:
playerModule.prototype.login = function(username, password) {
var o = this;
o.user.load(function (err) {
if (!err) {
o.user.authenticateUser(username, password, function(err, result) {
if (!result.userExists) {
console.log('Invalid username');
return "fail";
} else if (!result.passwordsMatch) {
console.log('Invalid password');
return "fail";
} else {
console.log('User token is: ' + result.token); <--- this is reached.
return result.token;
}
});
} else {
console.log('error logging in');
return "fail";
}
});
所以我猜我需要将值返回到“load”函数回调,但我不知道该怎么做。
答案 0 :(得分:1)
使用以下内容更改login
的定义。
playerModule.prototype.login = function(username, password, callback) {
var o = this;
o.user.load(function (err) {
if (!err) {
o.user.authenticateUser(username, password, function(err, result) {
if (!result.userExists) {
console.log('Invalid username');
return callback("fail");
} else if (!result.passwordsMatch) {
console.log('Invalid password');
return callback("fail");
} else {
console.log('User token is: ' + result.token); <--- this is reached.
return callback(result.token);
}
});
} else {
console.log('error logging in');
return callback("fail");
}
});