在Nodejs中编写promise函数时,undefined不是函数

时间:2016-11-14 19:37:41

标签: javascript node.js promise bluebird

我正在尝试使用Bluebird promise Library编写我的函数。 我通过以下方式宣传了ldap-js的ldap-js的createClient函数:

    var Promise= require('bluebird'); //done at the beginning
        var createClientAsync = Promise.promisify(require('ldapjs').createClient);
getUser:function(user) {
    var memberRoles = [];
    var searchFilter = '(&(member='+user.dn+'))';
     var opts = {
           filter: searchFilter,
           scope: 'sub',
           attributes: ['dn']
         };

    createClientAsync({
           url: 'ldap://x.x.x.x:3889'
         })
         .then(function(client){
           return client.search('o=pic', opts);
         })
         .then(function(res) {
           res.on('searchEntry', function(entry) {
               console.log('entry: ' + JSON.stringify(entry.object));
               for (var role in roles) {
                 var mapping = roles[role];
                 if (mapping.group === entry.object.dn) {
                   memberRoles.push(role);
                 }
               }
             });
         })
         .then(function() {
             return memberRoles;
         });
}

我在createClientAsync上遇到错误undefined不是函数。

1 个答案:

答案 0 :(得分:0)

在简要阅读ldapjs文档后,我可以建议以下代码

getUser:function(user) {
    var searchFilter = '(&(member='+user.dn+'))';
    var opts = {
        filter: searchFilter,
        scope: 'sub',
        attributes: ['dn']
    };
    return createClientAsync({
        url: 'ldap://x.x.x.x:3889'
    })
    .then(function(client){
        return client.search('o=pic', opts);
    })
    .then(function(res) {
        var memberRoles = [];
        return new Promise(function(resolve, reject) {
            res.on('searchEntry', function(entry) {
                console.log('entry: ' + JSON.stringify(entry.object));
                for (var role in roles) {
                    var mapping = roles[role];
                    if (mapping.group === entry.object.dn) {
                        memberRoles.push(role);
                    }
                }
            });
            res.on('end', function() {
                resolve(memberRoles);
            });
        });
    });
}

注意"新承诺"和res.on('结束'一旦"搜索"完成后解决承诺

正如我所说,简要阅读文档,所以这可能完全无效:p