1

I am using ldapjs library in nodejs. I want to access the results of client.search outside of the function. Here is my code

items = [];
  client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
    if (err)
      console.log(err);
    res.on('searchEntry', function (entry) {
      items.push(entry.object);
    });
    res.on('error', function (err) {
      console.error('error: ' + err.message);
    });
    res.on('end', function (result) {
      console.log('status: ' + result.status); 
      console.log(items[0]);  **//Prints results correctly**   
    });
  });
console.log(items[0]); **//Prints []**

I tried return items inside search. Still doesn't print. Any suggestions?

user2406718
  • 263
  • 4
  • 15

2 Answers2

1

I encountered the same problem. Since res.on 'searchEntry' is an event emitter , a simple solution that I use is to wrap the whole thing in a promise and return that.

let search = function( 'cn=users,dc=test,dc=com', opts ) {

return new Promise( ( resolve, reject ) => { 
  items = [];
      client.search('cn=users,dc=test,dc=com', opts, function (err, res) {
        if (err)
          console.log(err);
          reject( err )
        res.on('searchEntry', function (entry) {
          items.push(entry.object);
        });
        res.on('error', function (err) {
          console.error('error: ' + err.message);
          reject( error )
        });
        res.on('end', function (result) {
          console.log('status: ' + result.status); 
          console.log(items[0]);  **//Prints results correctly**
          resolve( items )   
        });
      });
   }
};

Then you can do something like this:

let entries = await search( 'cn=users,dc=test,dc=com', opts );
0

You can use a wrapper function and a callback

function search(dn, options, callback){
  // your code ...
  res.on('end', function (result) {
    callback(items);
  }
});

and to call it like this

search(dn, options, function(err, result) {
    //your result ...
    console.log(result);
}
vgudzhev
  • 21
  • 6