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

3K
Views
How to do an If await by the async function response

I'm trying to create a function that checks if a table already exists in the database and if it doesn't, create one But the problem is the If doesn't await for checkTableExist()

const checkTableExist = async () => {
    console.log('starting check')
    db.query(`SELECT column_name
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE table_name = 'users'`, async (error, results) => {
        if (error) {
            console.log(error)
        }
        if (results !== null) {
            console.log('Not exist')
            return true
        }
        console.log('Exist')
        return false
    })
}


const createTable = async () => {
    await db.connect();
    if (await checkTableExist() !== true) {
        console.log('Creating Table')
        await db.query(`CREATE TABLE users (
             id SERIAL PRIMARY KEY,
             name varchar(100),
             email varchar(100),
             celular varchar(11),
             password varchar(255),
             validated boolean
         )`)
         db.end()
         return
    }
    db.end()
    console.log('Table already exist')
    return
}

createTable()

Console Log

starting check
Creating Table
Not exist
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

In checkTableExist you are checking your DB Query results using a callback function. In there, when you return, you are not actually returning to the createTable function, you're getting back to checkTableExist.

If you use await, your returns should work correctly:

const checkTableExist = async () => {
  console.log('starting check')

  const results = await db.query(`SELECT column_name FROM INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'users'`);

  if (results !== null) {
    console.log('Not exist')
    return true
  }
  console.log('Exist')
  return false
})
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!