Use ldapjs with bluebird promise

会有一股神秘感。 提交于 2020-01-13 10:42:09

问题


I posted something similar here: Use ldapjs with promise. Unfortunately, it is still unsolved.

This time I tried bluebird and hopefully I can get some luck.

// https://www.npmjs.com/package/ldapjs
var Promise = require('bluebird');
var ldap = Promise.promisifyAll( require('ldapjs') );
var config  = require('./config');
var print_r = require('print_r').print_r;


var my_filter = "(&(objectCategory=person)(objectClass=user)" + "(cn=" + 'someone' + "))";
var ldap_username = config.ad.username;
var ldap_password = config.ad.password;
var ldap_url = config.ad.url;
var ldap_dn_search = config.ad.dn_search;

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
ldap.Attribute.settings.guid_format = ldap.GUID_FORMAT_B;


var opts = {
  filter: my_filter,
  scope: 'sub',
};


//test
console.log(my_filter);
console.log(ldap_username);
console.log(ldap_password);
console.log(ldap_url);
console.log(ldap_dn_search);


/* NOTE: This code is working!!!
client.bind(ldap_username, ldap_password, function (err) {
  client.search(ldap_dn_search, opts, function (err, search) {
    search.on('searchEntry', function (entry) {
      var user = entry.object;
      console.log(user);
    });
  });  
});
*/

// I tried to rewrite the code above with promise
ldap.createClientAsync({
  url: ldap_url
})
.then(function(client){
  console.log('bind'); // No print
  return client.bindAsync(ldap_username, ldap_password);
})
.then(function() {
  console.log('search'); // No print
  return client.searchAsync(ldap_dn_search, opts);
})
.then(function(search) {
    // No flow here
  search.on('searchEntry', function (entry) {
    var user = entry.object;
    console.log(user);
  });
})

The script doesn't output anything. It is waiting for something in terminal.


回答1:


Using Bluebird Promises, the easy way to do this is to create your client normally, and then run the promisifyAll() on the client.

var ldap = require('ldapjs');
var Promise = require('bluebird');

var client = ldap.createClient({
  url: 'ldap://my-server:1234',
});

Promise.promisifyAll(client);

Now you can call client.addAsync() and client.searchAsync() and such.

client.bindAsync(secUserDn, secUserPassword)
  .then(doSearch) // if it works, call doSearch
  .catch(function (err) { // if bind fails, handle it
    console.error('Error on bind', err)
  });

function doSearch(data) {
  client.searchAsync('CN=A Test,OU=Users,DC=website,DC=com', options)
    .then(function (data) { // Handle the search result processing
      console.log('I got a result');
    })  
    .catch(function (err) { // Catch potential errors and handle them
      console.error('Error on search', err);
    });
}


来源:https://stackoverflow.com/questions/30802935/use-ldapjs-with-bluebird-promise

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!