node-ldapjs icon indicating copy to clipboard operation
node-ldapjs copied to clipboard

calling another search within client.search and res.on("searchEntry")

Open czkoudy opened this issue 3 years ago • 3 comments

Hi all,

Iam trying the following:

const getPhones = (callserver) => {
  const phones = [];
  const opts = {
    filter: `(objectClass=Phone)`,
    scope: 'sub',
  };
  return new Promise((resolve, reject) => {
    login(function () {
      client.search(`cn=${callserver === 'primary' ? primaryCS.cn : secondaryCS.cn},cn=Modules`, opts, function (err, res) {
        if (err) {
          console.log('Error in promise', err);
        }
        res.on('searchEntry', function (entry) {
          const opts = {
            filter: `(objectClass=*)`,
            scope: 'sub',
          };
          client.search(`${entry.object.dn}`, opts, function (err, res2) {
            res2.on('searchEntry', function (entry2) {
            phones.push({ ...entry.object, detail: entry2.object }); // this doesnt work, but if console entry2 just before this line it will console it correctly 
});
          });
        });
        res.on('end', function () {
          resolve(phones);
        });
        res.on('err', function () {
          reject('Error');
        });
      });
    });
  });
};

but its not working correctly.

i have opened issue on stack too: Here

could anyone help?

czkoudy avatar Mar 13 '21 16:03 czkoudy

It looks like you are resolving the first search before the second search returns a value.

UziTech avatar Mar 14 '21 05:03 UziTech

client.search(..., function (err, res) {
  res.on('searchEntry', function (entry) {
    console.log(1);
    client.search(..., function (err2, res2) {
      res2.on('searchEntry', function (entry2) {
        console.log(2);
      });
    });
  });
  res.on('end', function () {
    console.log(3);
  });
});

The previous code will log:

1
3
2

UziTech avatar Mar 14 '21 05:03 UziTech

You have to find a way to wait to resolve the promise until all searches are complete.

Something like:

let searches = 0
client.search(..., function (err, res) {
	searches++
  res.on('searchEntry', function (entry) {
    client.search(..., function (err2, res2) {
      searches++
      res2.on('searchEntry', function (entry2) {
        ...
      });
	    res2.on('end', function () {
        searches--
	      if (searches === 0) resolve()
	    });
    });
  });
  res.on('end', function () {
    searches--
    if (searches === 0) resolve()
  });
});

UziTech avatar Mar 14 '21 05:03 UziTech

👋

On February 22, 2023, we released version 3 of this library. As a result, we are closing this issue/pull request.

Please see issue #839 for more information, including how to proceed if you feel this closure is in error.

jsumners avatar Feb 22 '23 19:02 jsumners