2016-04-26 199 views
0

我试图去执行,与ldapjs,一个搜索,过滤器依赖于第一搜索Ldap.js:嵌套搜索

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”还没有被引用。

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

感谢

回答

0

谢谢num8er。

我终于用 “承诺,LDAP” 模块,基于ldapjs并承诺

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); 
    }); 
}); 
0

你无法看到事件的结果,当你做console.log(myObj)

由于异步行为,您对等待第二次检索结束的。

你已经把它 “对” 内:

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); 
});