You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js调用ldapjs的client.bind返回值未传递问题求助

问题原因

你的ldap_conn函数返回undefined的核心原因是**client.bind是异步操作**:调用ldap_conn()时,函数会立即执行完毕(不会等待client.bind的异步逻辑完成),而原函数本身没有返回语句,所以调用结果是undefined。回调函数里的return只能结束回调自身,无法将值传递给外层的ldap_conn函数。

解决方案

方案一:用Promise封装(推荐)

修改ldap3.js,将ldap_conn改为返回Promise对象:

var ldap = require('ldapjs');

var client = ldap.createClient({url: 'ldap://ldap-pr.tsl.bobo.com:389'});
const dn = 'uid=myname,ou=people, ou=teamMembers,ou=internal,o=bobo'
const password = 'mypassword'

function ldap_conn(){
    return new Promise((resolve, reject) => {
        client.bind(dn, password, function(error){
            if(error){
                console.log('认证失败')
                reject('not ok')
            }
            else{
                console.log('认证成功')
                resolve('ok')
            }
        })
    })
}

module.exports = {ldap_conn}; 

在test2.js中用两种方式接收结果:

方式1:async/await

const f = require('./ldap3');

async function checkLdapAuth() {
    try {
        const result = await f.ldap_conn();
        console.log(result); // 成功时输出ok
    } catch (err) {
        console.log(err); // 失败时输出not ok
    }
}

checkLdapAuth();

方式2:.then()链式调用

const f = require('./ldap3');

f.ldap_conn()
    .then(result => console.log(result)) // 成功输出ok
    .catch(err => console.log(err)); // 失败输出not ok

方案二:使用回调函数

修改ldap3.js,让ldap_conn接收一个回调参数:

var ldap = require('ldapjs');

var client = ldap.createClient({url: 'ldap://ldap-pr.tsl.bobo.com:389'});
const dn = 'uid=myname,ou=people, ou=teamMembers,ou=internal,o=bobo'
const password = 'mypassword'

function ldap_conn(callback){
    client.bind(dn, password, function(error){
        if(error){
            console.log('认证失败')
            callback('not ok')
        }
        else{
            console.log('认证成功')
            callback('ok')
        }
    })
}

module.exports = {ldap_conn}; 

在test2.js中通过回调获取结果:

const f = require('./ldap3');

f.ldap_conn((result) => {
    console.log(result); // 成功输出ok,失败输出not ok
});

内容的提问来源于stack exchange,提问作者user14852478

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 19:52:33