I'm trying to write a Node.JS MySQL application, and I'm running in to an Async issue. Although I can console log the result right before returning it, it displays as "undefined" on the front side (index.js). What am I doing wrong here, and how can I change this?
connections.js
const mysql = require('mysql2');
const db = mysql.createConnection(
{
host: 'localhost',
user: 'root',
password: 'Password1',
database: 'employee'
},
);
module.exports = db;
index.js
const inquirer = require('inquirer');
const db = require('./db/connections');
const cTable = require('console.table');
const { getDepartments, addDepartment } = require('./utils/departmentFunctions');
let endProgram = false;
const mainMenuQuestions = [
{
type: 'list',
name: 'next',
message: '? What would you like to do?',
choices: ['View All Employees', 'Add Employee', 'Update Employee Role', 'View All Roles', 'Add Role', 'View All Departments', 'Add Department', 'Quit', ]
}
];
const promptUser = () => {
return inquirer.prompt(mainMenuQuestions);
}
async function startApp() {
let isFinished = false;
while(!isFinished) {
let next = await promptUser();
if(next.next === 'View All Departments') {
console.log(``);
await console.log(getDepartments());
console.log(``);
} else if(next.next === 'Add Department') {
addDepartment();
} else if(next.next === 'View All Employees') {
}else if(next.next === 'Add Employee') {
} else if(next.next === 'Update Employee Role') {
} else if(next.next === 'View All Roles') {
} else if(next.next === 'Add Role') {
} else {
isFinished = true;
}
}
}
startApp();
departmentFunctions.js
const db = require('../db/connections');
const inquirer = require('inquirer');
const cTable = require('console.table');
getDepartments = () => {
db.query(`SELECT * FROM departments`, function(err, results, fields) {
console.log(results);
return results;
});
};
module.exports = {
getDepartments
};
CodePudding user response:
In index.js
you have this:
await console.log(getDepartments());
But this console.log
is destroying the intended effect of await
:
console.log
is executed synchronously (it doesn't wait for thegetDepartments()
promise to resolve), and outputs a pending promise object.console.log
itself returnsundefined
, andawait
will interpret that is a resolved promise withundefined
as fulfillment value. As a consequence, the execution will be restored in the next tick and resume while the promise you really wanted to wait for is still pending.
To correct this, put the console.log
in the asynchronous part of the code (i.e. after getDepartments()
resolved):
const departments = await getDepartments();
console.log(departments);