I am taking an email from the user and checking it in the database(DB2). After that I am sending an HTTP get request to further verify that email from a remote server. After that I am executing the query to verify the user password. However, I am facing a race condition here. My query for password verification begins executing without waiting for the API response from the remote server. How can I resolve that?
Here's my code:
conn.query(searchDB, [email], (err, results) => {
if(!err)
{
if(results.length == 0)
{
res.send("UnAuthorized");
}
else
{
// I get the response from the below request
samaccount = results[0].samaccount;
http.get(`API-endpoint/${samaccount}`, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
newdata = JSON.parse(data);
if(newdata.accountStatus == true)
{
samaccountvalid = true;
console.log("User Authorized as per sam account");
}
else
{
samaccountvalid = false;
console.log("User NOT Authorized as per sam account");
return;
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
});
//at the same time this starts executing I want to wait for the above request to complete
if(samaccountvalid == true)
{
console.log("Password is being compared");
.....comparing password here.....
}
........
Any help would be appreciated. Thanks!