0

I set up the promise function via:


const mysql = require('mysql2');
const util = require('util');
require('dotenv').config();


const db = mysql.createConnection(
    {
        host: 'localhost',
        user: process.env.DB_USER,
        password: process.env.DB_PASSWORD,
        database: process.env.DB_NAME
        

    },

    console.log(`Connected to the employeetracker_db database.`)
);

const query = util.promisify(db.query).bind(db);

I want to select all job roles in my database and then input it into my inquirer choices field for a question via:

const getAllRoles = async () => {
    await query(`SELECT title AS 'Job Title' FROM role;`, (err,results) => {
        if (err) {
            console.log(err);
        } else {
            results.map(function(results) {
            return results['Job Title']});
           };
        });
    };
    
const roles = getAllRoles().then((results)=> {
    return results;
});
console.log(roles);

However, no matter what permutation of async/await, synchronous functions, and .then() statements I've tried, I'm getting either undefined (if I don't promisify this) or Promise {<pending>}. I've tried using .then with a "return results" cb function on roles, I've tried adding await to the .map cb function. How do I get the promise to resolve and get my data?

DSwecker
  • 1
  • 2
  • 1
    Not an answer, but you might prefer to just import from `mysql2/promise` instead of `mysql2` + using promisify. – Evert May 11 '23 at 06:48
  • I tried that using the mysql2 documentation and still got a pending promise. Not saying I necessarily implemented it perfectly, but I basically just copy/pasted their documentation for setting up `mysql/promise` and the function still returned a pending promise rather than give me the array. – DSwecker May 11 '23 at 13:10
  • If you got a pending promise, you need to await it. I actually wrote a small guide for people getting started with MySQL in node: https://evertpot.com/executing-a-mysql-query-in-nodejs/ – Evert May 11 '23 at 17:39

0 Answers0