1

I'm using mysql2 and trying to create a module I can import through my app to access the connection pool. What I currently have returns a promise that I have to resolve every time I import it, but I'd prefer to resolve the promise before exporting. Is something like below possible?

// db.js
const config = require('./configs/config');
const mysql = require('mysql2/promise');

const pool = mysql.createPool({
        host: config.db.host,
        user: config.db.user,
        database: config.db.database,
        password: config.db.password,
        waitForConnections: true,
        connectionLimit: 10,
        queueLimit: 0,
        charset: 'UTF8MB4_GENERAL_CI'
    });

module.exports = await pool;

I've read a lot of questions and they seem to point to yes, but everything I try returns SyntaxError: await is only valid in async functions and the top level bodies of modules. Maybe I'm misunderstanding what top level bodies means. I'm using Node v16.13.2. Is there a better way to do this? Thanks!

NicholasJohn16
  • 2,390
  • 2
  • 21
  • 45

0 Answers0