Skip to content
Advertisement

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

Advertisement

Answer

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
})
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement