Home > Software engineering >  Nodejs Mysql asynchronous
Nodejs Mysql asynchronous

Time:06-28

I'm trying to return my users list from my Mysql database through this endpoint.

The problem is that it return "undefined".

Do you know how to solv this?

Thx in advance :)

app.get("/users", async (req, res) => {
  users = await query_my_users_from_db()
  // Got "users = undefined" here
  console.log(users)
  return JSON.stringify(users)
})

async function query_my_users_from_db() {
  var users = await db.query("SELECT * FROM `users`", function (err, result) {
    if (err) throw err
    users = Object.values(JSON.parse(JSON.stringify(result)))
    return users
  })
}

CodePudding user response:

Since db.query is callback based, you should change your code into:

function query_my_users_from_db(callback) {
   db.query("SELECT * FROM `users`", callback)
}

remove all the async\await since you are not using any promises!

then define your callback

const usersHandler = (err, result) => {
 ... do what you want with your users ...
}

and use it like this:

query_my_users_from_db(usersHandler)

Another option is to use some promise-based wrapper package for MySQL, there is plenty or use node util.promisify() (https://www.geeksforgeeks.org/node-js-util-promisify-method/) and then use async\await and remove the callback altogether.

Hope that it helps

CodePudding user response:

I used this and it's working like a charm.

db.promise = (sql, params) => {
      return new Promise((resolve, reject) => {
        db.query(sql, params, (err, result) => {
          if (err) {
            reject(new Error())
          } else {
            resolve(result)
          }
        })
      })
    }

    async function connection(query) {
      const result = await db.promise(query)
      return result
    }

    app.get("/users", async (req, res) => {
      users = await connection("SELECT * FROM `users`")
      return users
    })
  • Related