简体   繁体   中英

Async Mysql Query in Node.js

I want to get a specific value from my mysql database and then pass it to an API. So I have to wait for the query to finish. I found this async/await example on stackoverflow. But it's not working for me.

async function getUTC() {
  try {
    let result = await db.query(`SELECT utcEndSeconds FROM mp_games ORDER BY utcEndSeconds ASC LIMIT 1`)
    return result
  } catch (err) {
    console.log(err)
  }
}

let newUTC = getUTC()
console.log(newUTC)

newUTC.then(data => {
  console.log(data)
})

The first console.log(newUTC) prints Promise { pending }. I expected to find my data here, because await should already resolve the promise???

Then I added the.then() block. console.log(data) prints a big object (mysql I guess) but my data is nowhere to be found in the object.

What am I missing here? Thanks in advance.

You have problems with understanding of async/await pattern.

newUTC.then(data => {
  console.log(data)
})

the above code resolves promise and return you data object. but console.log(newUTC) gives you promise pending because it is not awaited nor encapsulated with promise for resolution.

if you change

let newUTC = getUTC()
console.log(newUTC)

to

let newUTC = getUTC()
console.log(await newUTC)

then first the code awaited and the result is passed to the console.log .

EDIT: await only works within async function. IF your function is not async then you need to use promise approach.

let newUTC = getUTC()
newUTC.then(data => console.log(data));

I think it's easier to use mysql.query callback function and run the rest of my code inside. It's not as pretty but works

db.query(`SELECT utcEndSeconds FROM mp_games ORDER BY utcEndSeconds ASC LIMIT 1`, (err, result) => {
  let newUTC = result[0].utcEndSeconds

... rest of my code (api calls etc...)

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM