I'm trying to make a SELECT query in my database using mysql nodejs module. The problem is that connection.query
function is an asyncronous function so I put it inside a promise like this:
function execQuery(query, fields){
const connection = mysql.createConnection({
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
return new Promise((resolve, reject) => {
connection.query(query, fields, (err, results) => {
connection.end();
if (err){
return reject(err);
}else{
return resolve(results);
}
}
)
This function is called by another function:
function getPasswordFromUser(username){
query = 'SELECT password FROM User WHERE username=?'
parameters = [username]
execQuery(query, parameters)
.then(result => {
if (result !== undefined && result.length === 1){
console.log('here1')
return result
}
})
.catch(err => console.log(err))
console.log('here2')
}
the problem is that despite I return a promise and use then
, in my console I receive:
here2
here1
So my query keeps running in asynchronous mode and I can't get the result.
What is the best way to do this using promise?
Simply you are not returning the promise, and that's it.
do: return execQuery(query, parameters)
And you use it like a simple promise.
getPasswordFromUser('userid')
.then((result)=>{
..do stuff..
});
or if you are using async-await
use a async function and await the getPasswordFromUser
function. For example for an express route.
app.post('/getPassword', async (req,res) =>{
const userID = req.body.userID;
const password = await getPasswordFromUser(userID);
res.send(password);
});
Note: The route is a joke, I hope you are not storing password in plain text, and if you want to match the password(like login) you should do something like: select count(*) from user where username=username and password=hash(password);
or maybe you are matching the password using bcrypt
or something.
You're seeing here2
first because it's not inside the then
. The program continues to execute after it starts the execQuery
function.
You can return a promise:
function getPasswordFromUser(username){
query = 'SELECT password FROM User WHERE username=?'
parameters = [username]
return execQuery(query, parameters)
.then(result => {
if (result !== undefined && result.length === 1){
console.log('here1')
return result
}
})
.catch(err => console.log(err))
}
Then add .then(result => { ... })
to the function call to get the result.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.