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

Viewed 3095

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}`);
    }
}
4 Answers

it must be inside async. ex:

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

This means that the function in which the call to queryDatabaseExists is performed must also be async, in order to use the await keyword inside it. The queryDatabaseExists function itself looks correct.

queryDatabaseExists function need to return promise if not you cannot use await

await command expect a promise to be return by the function link

let exists = await queryDatabaseExists(uniqueQuery, res);

await can only be used in async function. For your scenario you wanted wait for result from uniquequery. First you have to make change in your router.post callback like router.post('/url',async(req,res)=>{}); for making a synchornus call to checkifexist function. Second in order to use await in checkifexist function you have to make changes to checkisexist function to async function checkifexist(){}. Thirdly you wanted to wait for DB response for that you have use await while calling checkifexist function --> let result=await checkifexist(). you can check MDN website for better understanding.

router.post('url',async(req,res)=>{// in order to use await in checkifexist
//your rest of the code.
let result=await checkifexist();// waiting for db result
async function checkifexist(){//your awaited code.}
console.log(result);
});
Related