[Fixed] NodeJS Express app await is only valid in async function but this clearly is async function?

Issue

I have made a function to check if a certain thing already exists in the database. I have simply copy-pasted the logic I’m using to get something in the database and changed the query object + what is returned. But now it seems that node doesn’t like that and just throws an error that makes no sense to me.

Where I call the function:

let exists = await queryDatabaseExists(uniqueQuery, res);

The function that I’m calling:

async function queryDatabaseExists(queryParam, res) {
    try {
        const cp = new sql.ConnectionPool(config);
        await cp.connect();
        let result = await cp.request().query(queryParam);
        if(result.recordset.rowsAffected[0] = 1){return true} else { return false }
    } catch (err) {
        res.status(520).send(`Database error: ${err}`);
    }
}

The error that I’m getting:

let exists = await queryDatabaseExists(uniqueQuery, res);
             ^^^^^

SyntaxError: await is only valid in async function

ALL code for that route:

router.post("/admin/category", (req, res) => {

    uniqueQuery = `SELECT [name] from [dbo].[idtTV_categories] WHERE [name] = '${req.body.name}'`

    getQuery = `SELECT [id]
    ,[name]
    ,[description]
    ,[created_time]
    ,[created_by] from [dbo].[idtTV_categories]`

    standardQuery = `INSERT INTO [dbo].[idtTV_categories] ([name],[description],[created_time],[created_by]) 
    VALUES 
    ('${req.body.name}', 
    '${req.body.description}',
    SYSDATETIME(),
    '${req.user.name}')`;

    let exists = checkIfExists();

    function checkIfExists() { result = await queryDatabaseExists(uniqueQuery, res); return result} ;

    console.log(exists);

    if(req.user.roles.some(role => role === admin || role === editor)){
        if(!existsInDatabase){
        if(queryDatabase(standardQuery, res)){queryDatabase_get(getQuery, res)}
    }
}

    else { res.statusMessage = `${req.user.name} is not authorized to add categories.`;
           console.log(req.user.roles)
           res.status(520).send() };

})

All functions being called:

///////////// MAIN QUERYING FUNCTION //////////////////////
async function queryDatabase_get(queryParam, res) {
    try {
        const cp = new sql.ConnectionPool(config);
        await cp.connect();
        let result = await cp.request().query(queryParam);
        res.send(result.recordset);
    } catch (err) {
        res.status(520).send(`Database error: ${err}`);
    }
}

async function queryDatabaseExists(queryParam, res) {
    try {
        const cp = new sql.ConnectionPool(config);
        await cp.connect();
        let result = await cp.request().query(queryParam);
        if(result.recordset.rowsAffected[0] = 1){return true} else { return false }
    } catch (err) {
        res.status(520).send();
    }
}

async function queryDatabase(queryParam, res) {
    try {
        const cp = new sql.ConnectionPool(config);
        await cp.connect();
        let result = await cp.request().query(queryParam);
        if(result.rowsAffected > 0){ return true }
    } catch (err) {
        res.status(520).send(`Database error: ${err}`);
    }
}

Solution

it must be inside async.
ex:

app.post('/', async (req, res) => {
  let exists = await queryDatabaseExists(uniqueQuery, res);
});

Leave a Reply

(*) Required, Your email will not be published