I am trying to implement a use case where users can request to check his password by providing username. Issue: Node js back-end app returns result before query is complete. I have checked articles explaining async aspect of javascript. However, I am still unsure if the solutions can be applied when there is a rest call involved in between.
High level flow:
- Front-end js calls rest api(node.js application) with username to get password
- Node app calls DB to get password
- Returned password is displayed on front end
Code:
Front-end:
function getPassword() {//Called by clicking button on ui
var username = 'testuser'; //hardcoding for simplicity
$.ajax({
url: urlWhereNodeJsAppIsHosted,
error: function(password) {
console.log('error' + JSON.stringify(password));
}, success: function(data) {
console.log('success' + JSON.stringify(password)); // Displaying on console for now
}
});
}
Back-end(Node js app):
const express = require('express');
const request = require('request');
const mysql = require('mysql');
const app = express();
var connection = mysql.createConnection({
host: 'localhost',
port: '3306',
user: 'dbuser',
password: 'dbuserpassword',
database: 'dbname'
});
connection.connect(function(err) {
if (err) {console.log(err);}
});
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
next();
});
app.get('/verify', (req, res) => {
var username = req.query.username;
var password = 'noresult';
connection.query(
'SELECT * FROM userpassword where user=?, ${[username]}',
function(err, rows, fields) {
password = extractpasswordfromrows(rows);//iterate and get result
}
);
console.log(connection.threadId); //Value is not undefined
res.send(200, { success: password });
});
const PORT = process.env.PORT || 3001;
app.listen(PORT, () => console.log(`listening on ${PORT}`));
Database:
userpassword(user, password) table with existing data.
I am new to javascript as well as thinking asynchronously. Please help with your inputs. Thanks.