最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - NodeJS Express app await is only valid in async function but this clearly is async function? - Stack Overflow

programmeradmin4浏览0评论

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

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}`);
    }
}
Share Improve this question edited Oct 31, 2018 at 22:26 marc_s 756k184 gold badges1.4k silver badges1.5k bronze badges asked Oct 25, 2018 at 15:39 SebastianGSebastianG 9,64418 gold badges66 silver badges148 bronze badges 14
  • is the function that thislet exists = await queryDatabaseExists(uniqueQuery, res); is in async as well? – Adam H Commented Oct 25, 2018 at 15:42
  • @AdamH I don't understand your question – SebastianG Commented Oct 25, 2018 at 15:43
  • You have the line let exists .... is that in a function? – Adam H Commented Oct 25, 2018 at 15:46
  • no, I'm trying to store the result of the async function as a boolean; – SebastianG Commented Oct 25, 2018 at 15:47
  • most likely you defined the variable 'exists' inside some function that is not async. Make that function async and it should solve the issue. – dev Commented Oct 25, 2018 at 15:47
 |  Show 9 more ments

4 Answers 4

Reset to default 7

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 mand 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);
});

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论