Hope everyone of you are doing well. I am stuck in a bit of problem. Any help will be highly appreciated.
I am using ldapJS and I want to call another promise from searchEntry method of LDAPJS. When i write the code same as below. it throws an error
exports.getADUsers = async (reqst, resp, next) => {
let flag = false;
var finalList = [];
let adConnStatus = await ConnectAD()
.then().catch((errConnStatus) => {
console.log("Error in connection with Active directory " + errConnStatus);
});
if (adConnStatus.status == 0) {
let client = adConnStatus.client;
const opts = {
filter: '(ObjectClass=*)',
scope: 'sub',
attributes: ['cn', 'sid', "objectSid"]
};
client.search('dc=domain,dc=com', opts, (err, res) => {
if (err) {
console.log("Error: " + err);
} else {
res.on('searchEntry', (entry) => {
finalList = await searchEntry(entry);
});
res.on('searchReference', (referral) => {
console.log('referral: ' + referral.uris.join());
});
res.on('error', (err) => {
console.error('error: ' + err.message);
});
res.on('end', (result) => {
resp.send(finalList);
console.log(result);
});
}
});
}
}
Error:
finalList = await searchEntry(entry);
^^^^^
SyntaxError: await is only valid in async function
Please help! how to call another promise from one promise. Though the method is async why it shows this message? what am i doing wrong?
EDIT
After adding the keyword async
as suggested by @Punth
. Also modifying a bit of the code. my new code is as follows.
exports.getADUsers = async (reqst, resp, next) => {
let adConnStatus = await ConnectAD()
.then().catch((errConnStatus) => {
console.log("Error in connection with Active directory " + errConnStatus);
});
if (adConnStatus.status == 0) {
var adUsersList = [];
let client = adConnStatus.client;
const opts = {
filter: '(ObjectClass=*)',
scope: 'sub',
attributes: ['cn', 'sid', "objectSid"]
};
client.search('dc=domain,dc=com', opts, (err, res) => {
if (err) {
console.log("Error: " + err);
} else {
res.on('searchEntry', async (entry) => {
var raw = entry.raw;
if (raw.objectSid != "undefined" && raw.objectSid != null && entry.object.cn != null && entry.object.cn != "undefined") {
let userData = {
"Name": entry.object.cn,
"SSID": sidBufferToString(raw.objectSid)
}
var lmn = await ConnectAndGetUsersList(userData.SSID);
userData["XYZ"] = lmn.xyz;
userData["ABC"] = lmn.abc;
adUsersList.push(userData);
}
});
res.on('searchReference', (referral) => {
console.log('referral: ' + referral.uris.join());
});
res.on('error', (err) => {
console.error('error: ' + err.message);
});
res.on('end', (result) => {
console.log(result);
resp.send(adUsersList);
});
}
});
}
}
By running the above code it doesn't shows me anything. res.on('end' ....)
is called prior to res.on("searchEntry"....)
Therefore the array of adUsersList
is null.
Now my question is how to resp.send
the final arraylist???