Hi as i am new to NodeJS as a follow-up to my previous question (Having problems getting new Array Value after looping in NodeJS) i have managed to get my code mostly working for parsing a list of email and querying them to the database, unable to get the return value in my promise when i get a response back from NodeJS API.
I am using MySQL 2.18.1 for my database and 4.17.1
Any idea i can solve it? Been trying it for a few hours.
Logs:
IM OUT HERE
Promise { { recipients: [] } }
{ recipients: [] }
retrieve_for_notification.js
async function processEmails(emails) {
var retrieveValues = {
recipients: []
};
// emails consist of those who were mentioned/notified, check condition whether they are eligible to be placed in receipients list
for (var i = 0; i < emails.length; i++) {
console.log(emails[i]);
// 1 - check for suspended
// 2 - check whether teacher and student pair is registered
var sql1 = 'SELECT COUNT(*) as count_value FROM school.schoolinformation WHERE email = ? AND user_status = ?';
var sql2 = 'SELECT COUNT(*) as count_value2 FROM school.registration_relationship WHERE teacher_email = ? AND student_email = ?';
var sql3 = 'SELECT COUNT(*) as count_value3 FROM school.schoolinformation WHERE email = ? AND user_type = ?';
var sqlvalues1 = [emails[i], 1];
var sqlvalues2 = [teacher, emails[i]];
var sqlvalues3 = [emails[i], 0];
// check for suspended
con.pool.query(sql1, sqlvalues1, async function (err1, result1) {
if (err1) throw err1;
var res1 = await getResult(sql1, sqlvalues1)
// console.log("(1) res value is %s", res1[0].count_value);
if (res1 > 0) return; // if result found skip to next email
// check whether teacher and student pair is registered
con.pool.query(sql2, sqlvalues2, async function (err2, result2) {
if (err2) throw err2;
var res2 = await getResult(sql2, sqlvalues2)
// teacher and student pair is not registered
if (res2 == 0) {
// check whether student mentioned is a valid student
con.pool.query(sql3, sqlvalues3, async function (err3, result3) {
if (err3) throw err3;
var res3 = await getResult(sql3, sqlvalues3)
// student is valid
if (res3 == 0) {
retrieveValues.recipients.push(sqlvalues3[0]);
}
});
}
else {
retrieveValues.recipients.push(sqlvalues2[0]);
}
});
});
};
return recipientsList;
}
var recipientsList = processEmails(emails);
console.log("IM OUT HERE");
console.log(recipientsList);
// Resolve promise and response send, not using helper for this
var p2 = Promise.resolve(recipientsList);
p2.then(function(v) {
console.log(v);
response.write(JSON.stringify(v, null, 3));
response.send.bind(response);
response.end();
}, function(e) {
console.error(e); // TypeError: Throwing
});
function getResult(sql, sqlvalues) {
// console.log("getResult SQL Query: %s", sql);
return new Promise(function (resolve, reject) {
con.pool.query(sql, sqlvalues, function (err, result) {
if (err) {
reject(err)
} else {
resolve(result)
}
})
})
}