Home > Net >  make mysql connection error in lambda, why?
make mysql connection error in lambda, why?

Time:12-22

I wonder difference to main, function

environment nodejs 14.x mysql2 2.2.3

I made code,

call pool.getconnection in main, it's fine(success data from db) but can't get a data from function.

I wonder why this can't get from function

const pool = mysql.createPool({
  host: SERVICE_INFO.DB_HOST,
  database: SERVICE_INFO.DB_NAME,
  user: SERVICE_INFO.DB_USERNAME,
  password: SERVICE_INFO.DB_PASSWORD,
  port: SERVICE_INFO.DB_PORT,
  connectionLimit: 20,
})

async function getData() {
  try {
    const connection = await pool.getConnection(async conn => conn) // error why??
    await connection.query(~~~)
  } catch (error) {
   
  }

}
module.exports.main = async (event) => {
 const connection = await pool.getConnection(async conn => conn);
 const result = await connection.query(`~~~`);
 connection.release()

}

can't find error log only find Promise pending.. Promise { }

CodePudding user response:

The getConnection method does not return a Promise, you should be able to retrieve the connection in the callback:

function getData() {
  pool.getConnection(async (err, conn) => {
    try {
      if (err) throw 'Something went wrong';
      await conn.query('<query>');
      pool.releaseConnection(conn);
    } catch (error) {
      console.log(error);
    }
  });
}

You can find an example in the docs.

  • Related