0

我正在尝试使用 ldapjs 执行搜索,过滤器取决于第一次搜索的结果

ldapClient.search(base1, opts1, (err1, res1) => {
    res1.on("searchEntry", entry => {
        const myObj = { attr1: entry.object.attr1 }
        const opts2 = { filter: entry.object.filter }

        if (entry.object.condition == myCondition) {
            ldapClient.search(base2, opts2, (err2, res2) => {
                res2.on("searchEntry", entry => {
                    myObj.attr2 = entry.object.attr2
                });
            });
        }

        console.log(myObj);
    });
});

问题是,当console.log 最后显示我的对象时,我的第二次搜索的事件“.on”还没有被特征化。

那么,如何告诉我的代码在显示对象之前等待第二个事件完成?

谢谢

4

2 回答 2

0

谢谢num8er。

我终于使用了“promised-ldap”模块,基于 ldapjs 和 promises

ldapClient.bind(dn, password).then(() => {

    let p;

    ldapClient.search(base1, opts1).then(res1 => {
        const entry = res1.entries[0].object;
        const myObj = { attr1: entry.attr1 };

        if (entry.condition == myCondition) {
            const opts2 = { filter: entry.filter }
            p = ldapClient.search(base2, opts2).then(res2 => {
                const entry2 = res2.entries[0].object;
                myObj.attr2 = entry2.attr2;
                return myObj;
            });
        } else {
            p = Promise.resolve(myObj);
        }

        p.then(value => console.log("Obj", value);
    });
});
于 2016-04-27T07:19:53.527 回答
0

当你这样做时,你看不到事件的结果console.log(myObj)

由于异步行为,您必须等待第二次搜索完成。

你必须把它放在“.on”里面:

ldapClient.search(base1, opts1, (err1, res1) => {
    res1.on("searchEntry", entry => {
        let myObj = { attr1: entry.object.attr1 }
        let opts2 = { filter: entry.object.filter }

        if (entry.object.condition == myCondition) {
            ldapClient.search(base2, opts2, (err2, res2) => {
                res2.on("searchEntry", entry => {
                    myObj.attr2 = entry.object.attr2
                    console.log("res2", myObj);
                });
            });
            return;
        }

        console.log("res1", myObj);
    });
});

也适用于优雅的代码你可以像这样使用它:

const async = require('async');

function ldapSearch(base, opts, callback) {
  ldapClient.search(base, opts, (err, res) => {
    if(err) return callback(err);

    res.on("searchEntry", entry => {
      callback(null, entry);
    });
  });
}

async.waterfall([
  function(done) {
    ldapSearch(base1, opts1, done);
  },
  function(entry, done) {
    if (entry.object.condition != myCondition) {
      return done("Condition not met");
    }

    let myObj = { attr1: entry.object.attr1 };
    let opts2 = { filter: entry.object.filter };
    ldapSearch(base2, opts2, (err, entry) => {
      myObj.attr2 = entry.object.attr2;
      done(null, myObj);
    });
  }
],
function(err, myObj) {
  if(err) {
    console.error(err);
    return;
  }

  console.log('MyObj', myObj);
});
于 2016-04-26T14:08:58.863 回答