0

I'm trying to make a function which returns the user's balance. However, the function returns undefined. I've checked all the solutions on stackoverflow but I wasn't able to find a solution.

Return func

    async function checkBal(username) {
        db.getConnection(async (err, connection) => {
            if (err) throw (err)
            let queryBal = `SELECT balance FROM user WHERE username = "${username}";`
            connection.query(queryBal, async (err, result) => {
                if (err) throw (err)
                if (result.length != 0) {
                    const data = result[0].balance
                    return data               

Function from which I'm calling

    app.post("/api/bet", urlencodedParser, async function(req, res){ 
        ssn = req.session;
        if (ssn.username) {
            balance = await checkBal(ssn.username)
            console.log(balance)
gx.
  • 3
  • 2
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – jabaa Apr 03 '22 at 15:44
  • You're `return`ing from the callback, not from `checkBal`. – Bergi Apr 03 '22 at 15:49
  • Does this answer your question? [How do I convert an existing callback API to promises?](https://stackoverflow.com/questions/22519784/how-do-i-convert-an-existing-callback-api-to-promises) – jabaa Apr 03 '22 at 15:50

1 Answers1

1

You need to return a Promise which will return the data through resolve when the function is done

async function checkBal(username) {
  return new Promise((resolve, reject) => {
      db.getConnection((err, connection) => {
        if (err) reject(err)
        let queryBal = `SELECT balance FROM user WHERE username = "${username}";`
        connection.query(queryBal, (err, result) => {
            if (err) reject(err)
            if (result.length != 0) {
                const data = result[0].balance
                resolve(data);
            }
        });
     });
  });
 }

And you don't need async in front of a function definition if there is no await in it.

(Also you should escape username because your code is vulnerable to SQL Injections)

Dj0ulo
  • 440
  • 4
  • 9