Search code examples
node.jsexpressasynchronouspromisemysql2

Is there anything wrong with async/await in my code


Express API with mysql2 I want to use the async and await to query the data from the product table but nothing print at all, don't know how to use it properly.

exports.getAllTours = function(req, res) {
  getTours()
  .then(data => console.log(data))
  .catch(err => console.log(err ));
}

async function getTours() {
    var sql = "Select * from product_prd"
    return new Promise(async function(resolve, reject) {
        let [rows, fields] = await poolQuery(sql)
        setTimeout(function() {
            resolve(rows);
        }, 500);
    })
    .catch(err => reject(err));
}

async function poolQuery(sql, args) {
    return new Promise((resolve, reject) => {
        promisePool.query(sql, args, (err, rows) => {
            if (err)
                return reject(err);
            resolve(rows);
        }).catch(err => reject(err));
    });
}

I created the pool of connection like this by following the official documentation of mysql2

const mysql = require('mysql2');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'super',
    port: '3307',
    password: 'sohail',
    database: '784413_wonder',
    waitForConnections: true,
    connectionLimit: 10,
    queueLimit: 0

});
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();

module.exports = promisePool;

Solution

  • I'm pretty sure there is a SQL error, and you cannot figure it out because the error handling in getTours is wrong.

    Try this:

    exports.getAllTours = function(req, res) {
      getTours()
      .then(data => console.log(data))
      .catch(err => console.log(err ));
    }
    
    async function getTours() {
        var sql = "Select * from product_prd"
            return new Promise(async function (resolve, reject) {
                let rows;
                let fields;
                try {
                    [rows, fields] = await promisePool.query(sql, args);
                } catch (err) {
                    reject(err);
                }
    
                setTimeout(function () {
                    resolve(rows);
                }, 500);
            });
    }