Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

141
Views
Combing async function and sql query

I'm new to async functions and I'm struggling getting it do work with db queries... Here's what I have:

fetch: async (id) => {
  if (id!=='something') {
    return await db.getConnection().query("SELECT user FROM `table` WHERE id='" + id + "'", function (err, result) {
      if (err) { throw err }
      else {
        console.log(result[0].user);
        return result[0].user;
      }
    });
  }
  throw new Error('Failed fetching installation');
}

This results in getting an error: Cannot read property 'user' of undefined , but after this error, the console.log comes in indicating result[0] is actually defined.

So my guess is that it's not waiting for the result or something like that (even though it's not hitting the throw new Error). Anyway, I'm sure this is just me not getting this right... as said, I'm only just getting started with these kinds of async behaviors.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

As mentioned above you are mixing promises and callbacks. I am unsure if my example below is possible with your database library, but I think if it is, its a much cleaner approach.

const fetch = async (id) => {
  if (id !== 'something') {
    try {
      const query = await db
        .getConnection()
        .query("SELECT user FROM `table` WHERE id='" + id + "'")
      return query[0].user
    } catch (error) {
      console.log(error)
      throw new Error(`Execution of query failed with error: ${error}`)
    }
  }
  throw new Error('Failed fetching installation')
}
const user = fetch('your-id') // (prefix fetch with await if not at top level)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!