0

I'm working on a script that insert and reads information on a mysql database. I've done the first step which is create registers on the database and works but I'm having issues reading the data out from the database.

I have a main.ts that call all the functions that performs the select/insert statements and a dao.ts with all the funtions that interact with the database.

This is the code where I call the function:

const vehiclesDB = select('SELECT * FROM vehicles', con);
console.log(vehiclesDB);

This is always returning undefined.

And this is the code that performs the sql statement:

    export const select = (statement: string, dbConnection: any) => {
    const results = dbConnection.query(statement, function (err, res, fields) {
        if (err) throw err;
        return res;
    });

    return results;
}

If I do a console.log on the res variable inside the select function I can see the result rows. I've tryed setting the results variable as return from the select function but what I can see on the main.ts then is the db connection details.

This is the library I'm working with to interact with mysql through node: https://github.com/mysqljs/mysql

jcobo1
  • 1,065
  • 1
  • 18
  • 34

1 Answers1

0

You are not returning any value from the function select. Also I don't think you can use both await and a callback for the query method. If the library only allows callbacks, wrap everything inside a Promise:

export const select = (statement: string, dbConnection: any) => {
    return new Promise((resolve, reject) => {
        dbConnection.query(statement, function (err, res, fields) {
            if (err) return reject(err);
            return resolve(res);
        });
    })
}

If the library allows the usage of Promises, you may want to try this:

export const select = (statement: string, dbConnection: any) => {
    return dbConnection.query(statement);
}

Also since you marked the function as aync it returns a Promise. You have to use await or .then() when calling the function.

const vehiclesDB = await select('SELECT * FROM vehicles', con);
Tobias S.
  • 21,159
  • 4
  • 27
  • 45
  • I've made the changes you mention, and removed the async I'm not sure that the async is needed, but on console.log(vehiclesDB) I get the connection details not the res value. I've updated the code. – jcobo1 Aug 23 '21 at 08:15
  • i updated my example, can you try the first code block and dont forget to use 'await' like in the last code block? – Tobias S. Aug 23 '21 at 08:18
  • returning a promise works but it's weird because none the examples I consulted uses promises, just in some cases async/await. – jcobo1 Aug 23 '21 at 08:23
  • the example in the second code block of mine is how most librarys do it today. When you mark a function as async, it always returns a Promise – Tobias S. Aug 23 '21 at 08:25