gpt4 book ai didi

javascript - 使用带有 Promise 的 ldapjs

转载 作者:行者123 更新时间:2023-12-02 16:06:16 25 4
gpt4 key购买 nike

我想将以下代码转换为使用 Promise。它正在工作并输出事件目录中的用户属性。

var client = ldap.createClient({
url: ldap_url
});

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;
// It is working!!!. It outputs all user attributes.
console.log(user);
});

});
});

以下是我的尝试,但它没有输出任何内容。

var Promise = require('promise');
var client_bind = Promise.denodeify(client.bind);
var client_search = Promise.denodeify(client.search);

client_bind(ldap_username, ldap_password)
.then(function(err){
client_search(ldap_dn_search, opts)
.then(function(search){
var search_on = Promise.denodeify(search.on);
search_on('searchEntry')
.then(function(entry){
var user = entry.object;

// It doesn't output anything !!!
console.log(user);
});
});

});

最佳答案

我也遇到了同样的问题。搜索会发出事件,因此我们需要一些东西来处理它们并沿着链进一步传递。这是一段适合我的代码:

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

var client = ldap.createClient({url: app.settings['ldap']['server']});
var uid;

promise.promisifyAll(client);

function searchPromise(res, notfoundtext) {
return new Promise(function(resolve, reject) {
var found = false;
res.on('searchEntry', function(entry) {
found = true;
resolve(entry);
});
res.on('error', function(e) {
reject(e.message);
});
res.on('end', function() {
if (!found) {
reject(notfoundtext);
}
});
});
}

client.searchAsync(app.settings['ldap']['baseDn'], {filter: '(mail='+credentials.email+')', scope: 'sub'})
.then(function(res) {
return searchPromise(res, 'User isn\'t exists.');
})
.then(function (entry) {
uid = entry.object.uid;
return client.bindAsync(entry.object.dn, credentials.password);
})
.then(function() {
return client.searchAsync('cn='+app.settings['ldap']['group']+',cn=groups,'+app.settings['ldap']['baseDn'], {scope: 'sub', filter: '(memberUid='+uid+')'});
})
.then(function(res) {
return searchPromise(res, 'User is not in group ' + app.settings['ldap']['group']);
})
.then(function() {
console.log('All is ok');
})
.catch(function(message) {
console.log('Error:' + message);
});

在搜索之后,我立即添加一个步骤来捕获事件,处理它们,并将其沿着链进一步传递。这使得函数 searchPromise 成立。

祝你编码顺利)

关于javascript - 使用带有 Promise 的 ldapjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30682597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com