Answer the question
In order to leave comments, you need to log in
How to get mysql query value outside of a function?
I have two files, index.js and db.js
In db.js I have a get_balance function that takes a user_id and inside it gets the desired user balance value for a given id.
The function itself:
function get_balance(user_id) {
conn.query(`SELECT * FROM users WHERE user_id = ${user_id}`, (err, result) => {
console.log(result[0].balance) // 0 (как и надо)
})
}
var results = get_balance(ctx.message.from.id)
console.log(results) // undefined
Answer the question
In order to leave comments, you need to log in
query is an asynchronous function. By the time the data is received from MySQL and the callback is called, the get_balance function itself has already completed.
Wrap the call in a Promise and use async/await. More or less like this:
async function get_balance(user_id) {
return new Promise((resolve, reject) => {
conn.query(
`SELECT * FROM users WHERE user_id = ${user_id}`,
(err, result) => {
if (err) {
reject(err);
}
console.log(result[0].balance) // 0 (как и надо)
resolve(result[0].balance);
},
);
});
}
const result = await get_balance(ctx.message.from.id);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question