Variable value remains unchanged after running multiple queries in Node JS
Solution 1:
This problem happened because you don't understand the promise event loop how work.
In your code db.query(query,values)
and if(uniqueUser) {
execute in same time in event loop and actually your variable uniqueUser
never changed.
You should change your code like bellow:
router.post('/register-user', multer_profile_pic.any(), (req, res, next) => {
var uniqueUser = true; //----> This value is being focused
const user = req.body;
var query = `SELECT * FROM users WHERE email=$1`;
var values = [user.email];
db.query(query, values)
.then(result => {
if (result.rowCount > 0) {
uniqueUser = false;
console.log('uniqueUser=' + uniqueUser); //----> Here value becomes false
}
if (uniqueUser) {
console.log(uniqueUser); //----> Here value becomes true
//INSERT QUERY HERE
return db.query('insert-query');
}
return Promise.resolve();
})
.then(() => {
const josn_resp = {
response: response,
message: message,
};
res.json(josn_resp);
})
.catch(err => {
res.status(400);
res.json({message: err.message})
});
});
If you use nodeJs 12 and above I suggest use async/await
:
router.post('/register-user', multer_profile_pic.any(), async (req, res, next) => {
const user = req.body;
try {
const result = await db.query(`SELECT * FROM users WHERE email=$1`, [user.email]);
if (result.rowCount === 0) {
await db.query('insert-query');
}
const josn_resp = {
response: response,
message: message,
};
res.json(josn_resp);
} catch (err) {
res.status(400);
res.json({message: err.message})
}
});