Typescript nested arrow function callback is not working as expeceted

Viewed 61

this.Pool

import mysql2 from 'mysql2/promise';

this.Pool = mysql2.createPool({   
            host : "1",
            user : "2",
            password : "3",
            database : "4"
           })
    async createTable(table: string): Promise<void> {
        await this.Pool.getConnection(async (connection) => {
            await connection.query(`CREATE TABLE IF NOT EXISTS \`${table}\`(
                a INT,
                b INT

            );`);
            console.log("TABLE CREATED");
        });
    }

in this case, the code just waits to get promise

    async createTable(table: string): Promise<void> {
        await this.Pool.getConnection(async (connection) => {
            return await connection.query(`CREATE TABLE IF NOT EXISTS \`${table}\`(
                a INT,
                b INT

            );`);
            console.log("TABLE CREATED");
        });
    }

but it just works..

this seems a bit different what I know. I know that Javascript automatically returns a Promise even if an asynchronous function does not return anything. is there something wrong in code or my knowledge?

2 Answers

Put your log statement between getting the value and returning it.

const ret =  await connection.query(`CREATE TABLE IF NOT EXISTS \`${table}\`(
                a INT,
                b INT

            );`);
console.log("TABLE CREATED");
return ret

Or inside the promise. (You do not need to even await in this case.)

return connection.query(`CREATE TABLE IF NOT EXISTS \`${table}\`(
                a INT,
                b INT

            );`).then(it=> {
              console.log("TABLE CREATED")
              return it 
})

As you said async function return promises if you don't return anything you should return the last operation of your code or variable .

Related