简体   繁体   English

奇怪的等待仅在异步函数错误中有效(nodejs)

[英]strange await is only valid in async functions error (nodejs)

so im getting this weird error that i can only use await in async function but im using it in an async funtion.所以我得到这个奇怪的错误,我只能在异步 function 中使用等待,但我在异步函数中使用它。 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.我正在使用节点 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}]}

You need to use async when you call a function. use your async on-调用 function 时需要使用异步。使用异步 on-

return new Promise( async resolve => {
            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.无论您在哪里使用 await,都应在 function 调用中声明异步。 Hope this will solve your issue.希望这能解决您的问题。

Your async keyword is not in the right place您的 async 关键字不在正确的位置

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM