1

I'm trying to get the data from LDAP and I'm getting it successfully but it's not written into variable so then after the code is executed I can make some checks on the data.

var server = LdapJS.createClient({
    url: LdapConf.server.url,
    tlsOptions: LdapConf.server.tlsOptions
});
server.bind(LdapConf.server.bindDN, LdapConf.server.bindCredentials, function(err) {
    if (err) {
        return done(err);
    }
});
var SearchOtps = {
    filter: '(uid=' + username + ')',
    scope: 'one',
};


var UserSearch = server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
    res.on('searchEntry', function(entry) {
        console.log('entry: ' + JSON.stringify(entry.object));
        return (JSON.stringify(entry.object));
    });
    res.on('searchReference', function(referral) {
        //console.log('referral: ' + referral.uris.join());
    });
    res.on('error', function(err) {
      //console.error('error: ' + err.message);
    });
    res.on('end', function(result) {
      //console.log('status: ' + result.status);
    });
});

console.log(UserSearch);

I just do not know how to stop further code execution while it's waiting for the return of the LDAP search.

Server Started
undefined
hplodur
  • 111
  • 3
  • 16

1 Answers1

0

You could do a function that returns it in promise.

function UserSearch(server,LdapConf, SearchOtps) {
  return new Promise(function(resolve,reject) {

    server.search(LdapConf.server.searchBase, SearchOtps, function(err, res) {
        res.on('searchEntry', function(entry) {
            console.log('entry: ' + JSON.stringify(entry.object));
            resolve(JSON.stringify(entry.object)));
        });
        res.on('searchReference', function(referral) {
            //console.log('referral: ' + referral.uris.join());
        });
        res.on('error', function(err) {
          reject()
        });
        res.on('end', function(result) {
          //console.log('status: ' + result.status);
        });
    });
  }
 }
 
 UserSearch(server,LdapConf, SearchOtps)
 .then(function(res) {
   console.log(res)
 })
anttud
  • 736
  • 3
  • 9
  • I've added the function but it seems that the only thing I'm getting is `[Function: getData]`. I did `var UserSearch = function getData() {` and your code. – hplodur May 02 '18 at 11:16
  • Corrected it with `var UserSearch = getData();` and I'm getting now `Promise { }` – hplodur May 02 '18 at 11:19
  • It is a promise so you need to call then to get the data, like in the example above :) If you are not familiar with promises they are simply explained [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) – anttud May 02 '18 at 11:23