Redberry
Redberry15mo ago

mysql query is skipped

Hi, I have a function that should retrieve data from the database and then process and return it. The function is however skipping the query and returning undefined. This is the query:
function getUser(name) {
client.query(`SELECT * FROM users WHERE name=? LIMIT 1`, [name]).then(data => {
// I want it to process and return the user data
})
// But it skips the query and returns undefined
}
function getUser(name) {
client.query(`SELECT * FROM users WHERE name=? LIMIT 1`, [name]).then(data => {
// I want it to process and return the user data
})
// But it skips the query and returns undefined
}
4 Replies
Redberry
RedberryOP15mo ago
Is there anyone who understands JS? Thanks
ioB
ioB15mo ago
You should probably study async/await: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Promises In this case you'd probably want to do
async function getUser(name) {
const data = await client.query(`SELECT * FROM users WHERE name=? LIMIT 1`, [name]);

// do stuff
return value;
}
async function getUser(name) {
const data = await client.query(`SELECT * FROM users WHERE name=? LIMIT 1`, [name]);

// do stuff
return value;
}
Redberry
RedberryOP15mo ago
I tried this before and it didn't work. Now that I tried it second time, it works.. I must've made a typo or something.. Thank you very much lino!
ioB
ioB15mo ago
👍