Eddy Blackpool
Eddy Blackpool

Reputation: 97

NodeJs + Mysql query execution too late (delays)

NodeJs + Mysql query execution too late (delays) https://github.com/mysqljs/mysql

Hello guys, I need help with mysql js, when I do .query(); the callback always delaying and gives me empty result but if I put timer it will give me the results, how do we fix the issue... on their documentation says this "Every method you invoke on a connection is queued and executed in sequence." so they using async i believe, anyone know how to wait for the results before sending data back to client side? I tried Promise, Async/Await but they using something else to stock up their queries..

con.query(`SELECT * FROM users`,
          function(err, data) {
            // this callback always delays 4 seconds, this callback executes straight away without waiting.
            return data;
          }
        );

Upvotes: 0

Views: 808

Answers (2)

Anupam
Anupam

Reputation: 47

Save the following file as QueryRunner.ts (Typescript). This will be your reusable component to run normal queries or parameterized queries. Then call 'executeQuery' function from your DAO layer as shown below.

export class QueryRunner {
private readonly connection: any;

constructor() {
    this.connection = require('mysql').createConnection({
        host: 'localhost',
        port: '3306',
        user: 'root',
        password: 'admin',
        database: 'quiz'
    });
};

public executeQuery(query:string, args?:any[]):any {
    return new Promise((resolve, reject)=> {
        this.connection.query(query, args,
        function(err, data) {
            if(err) {
                return reject(err);
            }
            console.log('QueryRunner: data = ');
            console.log(data);
            resolve(data);
        });
    })
};}

=========================================

export class DAO {
private readonly queryRunner: QueryRunner;

constructor() {
    this.queryRunner = new QueryRunner();
}

public getUsers(): any {
    let query: string = 'SELECT name, role FROM user_master';
    return this.queryRunner.executeQuery(query);
}}

Upvotes: 0

Igor Litvinovich
Igor Litvinovich

Reputation: 2502

There are a couple options how to handle this case, I'd recommend you to wrap your query in Promise as following:

    function getUsers() {
        return new Promise((resolve, reject)=> {
            con.query(`SELECT * FROM users`,
            function(err, data) {
                if(err) {
                    return reject(err);
                }
                resolve(data);
            });
        })
    }

    //usage 

    async function(req, res) {
        try {
            const users = await getUsers();
            res.send(users);
        } catch(error) {
            res.status(500).send(error)
        }
    }

Upvotes: 1

Related Questions