简体   繁体   中英

Ldapjs wait until search is completed

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 :)

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);
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM