Home > Back-end >  strange await is only valid in async functions error (nodejs)
strange await is only valid in async functions error (nodejs)

Time:03-10

so im getting this weird error that i can only use await in async function but im using it in an async funtion. The weird thing is i wasnt getting this error before i was editing another file and now im getting this error. I also found nothing online what might be causing this error.

Im using node v16.14.0.

This is my code:

"use strict";

const mariadb = require("mariadb");

class DBManager {
    constructor(logger) {
        if (logger === null || logger === undefined) throw "DBManager Logger referenz null oder undefined!";
        
        this.connectionPool = mariadb.createPool({
            host: process.env.DB_HOST,
            user: process.env.DB_USER,
            password: process.env.DB_PASSWORD,
            database: process.env.DB_DATABASE,
            connectionLimit: process.env.DB_MAX_CONNECTIONS,
            connectTimeout: 60
        });

        logger.info("DBManager initialisiert!")

        this.checkIntegrity();
    }

    async query(query, args) {
        return new Promise((resolve, reject) => {
            if (typeof(query) !== "string" || query == undefined) reject("ERR_INVALID_QUERY");

            logger.info("Führe Datenbankabfrage: "   query   " mit parametern: "   args   " aus.");

            this.connectionPool.getConnection()
            .then (connection => {
                connection.query(query, args)
                .then(rows => {
                    connection.release();
                    delete rows["meta"];
                    logger.info("Datenbankabfrage erfolgreich ausgeführt.")
                    resolve(rows[0]);
                })
                .catch (error => {
                    logger.error(error);
                    reject("ERR_MARIADB_QUERY_ERROR");
                });
            })
            .catch(error => {
                logger.error(error);
                reject("ERR_MARIADB_NO_CONNECTION");
            });
        });
    }

    async checkIntegrity() {
        return new Promise(resolve => {
            logger.info('Überprüfe ob alle Tabellen vorhanden sind.')
            let tableCheck = await this.checkTables();
        });
    }

    async checkTables() {
        return new Promise((resolve, reject) => {
            const query = "SELECT COUNT(*) AS tables_found_count FROM `information_schema`.`tables`  WHERE `TABLE_SCHEMA` = 'kaffeeportal' AND `TABLE_NAME` IN ('users', 'coffees', 'invoices');";
            const result = await this.query(query, []);
            
            if (result['tables_found_count'] == 3) resolve("TABLES_OK");
            else reject("ERR_TABLES_NOT_OK");
        });
    }

}

module.exports = DBManager;

And this is the error i get:

error: uncaughtException: await is only valid in async functions and the top level bodies of modules
/home/user/kaffeeportal-backend/src/dbmanager.js:53
            let tableCheck = await this.checkTables();
                             ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1032:15)
    at Module._compile (node:internal/modules/cjs/loader:1067:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/home/user/kaffeeportal-backend/src/main.js:7:19)
    at Module._compile (node:internal/modules/cjs/loader:1103:14) {"date":"Thu Mar 10 2022 11:20:37 GMT 0100 (Mitteleuropäische Normalzeit)","error":{},"exception":true,"os":{"loadavg":[0.81,0.39,0.36],"uptime":134976.5},"process":{"argv":["/usr/bin/node","/home/user/kaffeeportal-backend/src/main.js"],"cwd":"/home/user/kaffeeportal-backend","execPath":"/usr/bin/node","gid":1000,"memoryUsage":{"arrayBuffers":268937,"external":1860975,"heapTotal":17653760,"heapUsed":10289536,"rss":50532352},"pid":75934,"uid":1000,"version":"v16.14.0"},"stack":"/home/user/kaffeeportal-backend/src/dbmanager.js:53\n            let tableCheck = await this.checkTables();\n                             ^^^^^\n\nSyntaxError: await is only valid in async functions and the top level bodies of modules\n    at Object.compileFunction (node:vm:352:18)\n    at wrapSafe (node:internal/modules/cjs/loader:1032:15)\n    at Module._compile (node:internal/modules/cjs/loader:1067:27)\n    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)\n    at Module.load (node:internal/modules/cjs/loader:981:32)\n    at Function.Module._load (node:internal/modules/cjs/loader:822:12)\n    at Module.require (node:internal/modules/cjs/loader:1005:19)\n    at require (node:internal/modules/cjs/helpers:102:18)\n    at Object.<anonymous> (/home/user/kaffeeportal-backend/src/main.js:7:19)\n    at Module._compile (node:internal/modules/cjs/loader:1103:14)","timestamp":"2022-03-10T10:20:37.568Z","trace":[{"column":18,"file":"node:vm","function":"Object.compileFunction","line":352,"method":"compileFunction","native":false},{"column":15,"file":"node:internal/modules/cjs/loader","function":"wrapSafe","line":1032,"method":null,"native":false},{"column":27,"file":"node:internal/modules/cjs/loader","function":"Module._compile","line":1067,"method":"_compile","native":false},{"column":10,"file":"node:internal/modules/cjs/loader","function":"Module._extensions..js","line":1155,"method":".js","native":false},{"column":32,"file":"node:internal/modules/cjs/loader","function":"Module.load","line":981,"method":"load","native":false},{"column":12,"file":"node:internal/modules/cjs/loader","function":"Module._load","line":822,"method":"_load","native":false},{"column":19,"file":"node:internal/modules/cjs/loader","function":"Module.require","line":1005,"method":"require","native":false},{"column":18,"file":"node:internal/modules/cjs/helpers","function":"require","line":102,"method":null,"native":false},{"column":19,"file":"/home/user/kaffeeportal-backend/src/main.js","function":null,"line":7,"method":null,"native":false},{"column":14,"file":"node:internal/modules/cjs/loader","function":"Module._compile","line":1103,"method":"_compile","native":false}]}

CodePudding user response:

You need to use async when you call a function. use your async on-

return new Promise( asyncresolve => {
            logger.info('Überprüfe ob alle Tabellen vorhanden sind.')
            let tableCheck = await this.checkTables();
        });

wherever you use await declare the async on your function call. Hope this will solve your issue.

CodePudding user response:

Your async keyword is not in the right place

Update your code like this :

    checkIntegrity() {
        return new Promise( async function (resolve, reject) {
            logger.info('Überprüfe ob alle Tabellen vorhanden sind.')
            let tableCheck = await this.checkTables();
        });
    }
    
   checkTables() {
        return new Promise( async function (resolve, reject) {
            const query = "SELECT COUNT(*) AS tables_found_count FROM `information_schema`.`tables`  WHERE `TABLE_SCHEMA` = 'kaffeeportal' AND `TABLE_NAME` IN ('users', 'coffees', 'invoices');";
            const result = await this.query(query, []);
            
            if (result['tables_found_count'] == 3) resolve("TABLES_OK");
            else reject("ERR_TABLES_NOT_OK");
        });
    }
  • Related