I
I
iMainDay2021-08-20 21:06:33
MySQL
iMainDay, 2021-08-20 21:06:33

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 (как и надо)
    })
}

How can I correctly get the value of the executed get_balance function in index.js?
Tried to get it like this:
var results  = get_balance(ctx.message.from.id)
console.log(results) // undefined

Tried many different ways:
Both using return result[0].balance and using variables, nothing has helped so far.
All the time, undefined is returned in index.js, but if you return the value in the function, then everything returns fine, but I need to display result[0].balance in index.js.
Please do not beat with sticks, still green in this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2021-08-20
@iMainDay

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 question

Ask a Question

731 491 924 answers to any question