Reputation: 47
I have the Problem that the return is made before methodStatus is set to true (so the return is always false even when I can see 'success' in the console log)
function anmelden(username, userPassword){
var methodStatus = false;
var opts = {
filter: 'sAMAccountName=' + username,
scope: 'sub'
};
ldapClient.search('OU=secret,OU=secret,DC=secret,DC=secret', opts, function(err, res) {
res.on('searchEntry', function(entry) {
var userClient = ldap.createClient({url: 'ldap://secret:1111'});
userClient.bind(entry.object.dn + '', userPassword, function(err) {
if(err) {
console.log('failed')
methodStatus = false;
} else {
console.log('success')
methodStatus = true;
}
ldapBind();
});
});
console.log('end');
return methodStatus;
});
}
This is the console log:
end
success
Thank you for your help :)
Upvotes: 1
Views: 2208
Reputation: 443
it is because of asynchrony. the return
is invoked before the callback of the res.on
is invoked. there are a lot of ways to handle it, for example to add a callback to the anmelden
and to invoke it when the work is done:
function anmelden(username, userPassword, callback){
var methodStatus = false;
var opts = {
filter: 'sAMAccountName=' + username,
scope: 'sub'
};
ldapClient.search('OU=secret,OU=secret,DC=secret,DC=secret', opts, function(err, res) {
res.on('searchEntry', function(entry) {
var userClient = ldap.createClient({url: 'ldap://secret:1111'});
userClient.bind(entry.object.dn + '', userPassword, function(err) {
if(err) {
console.log('failed')
methodStatus = false;
} else {
console.log('success')
methodStatus = true;
}
ldapBind();
});
});
res.on('end', function () {
callback(methodStatus);
});
});
}
and to invoke it in the way like this:
anmelden('user', 'pass', function (methodStatus){
console.log('the status is %s', methodStatus);
})
Upvotes: 2