2016-04-26 124 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); 
});