Summary
I'm working on a project for school that requires us to use Inquirer to help users navigate an SQL database. I've boiled down my question to a minimum example.
Basically, my main init()
function continuously loops through an Inquirer prompt asking them what they want to do. I take their response, plug it into a switch
statement, and perform the correct action based on the user's choice. Easy.
But then when I try to again await the call from the second prompt, the main "action" prompt actually triggers again, where the prompts are populating each other within the console. I don't really know how to describe it, but it's not what I expect.
Code
import inquirer from "inquirer";
import { employeeQuestions } from "./lib/questions.js";
const prompt = inquirer.prompt;
const actionQuestions = [{
name: "action",
type: "list",
message: "Welcome! What would you like to do?",
choices: [
"View all Employees",
"Add an Employee",
"Exit"
]
}];
// This function handles the action chosen by the user in the main loop
const performAction = async (action) => {
switch (action) {
case "View all Employees":
console.log("Not yet implmented...");
break;
// HERE IS WHERE THINGS BREAK DOWN
case "Add an Employee":
let employeeData = await prompt(employeeQuestions); // Grab the employee data by awaiting prompt
console.log(employeeData); // Console out the data
break;
default:
break;
}
}
// Main logic flow
const init = async () => {
let action;
// While the user has not chosen to exit...
while (action != "Exit") {
action = (await prompt(actionQuestions)).action; // Get their choice by awaiting a prompt
performAction(action); // Perform that chosen action
}
}
init();
Expectation:
I would expect the program to pause at let employeeData = await prompt(employeeQuestions);
and not proceed in that switch/case block until the user has responded.
Observation:
Instead, both prompts begin running at the same time.
Moving forward
View all Employees
(and similar cases left out for simplicity) would select data from SQL and display a table, but we're also asked to implement the ability to view as sorted by different columns, which would be an additional inquirer call.Add an Employee
(and similar cases left out for simplicity) would need to perform SQL queries then to make those changes to the database, which not only sometimes necessitate an additional inquirer call for the relevant information but also somethings multiple SQL calls in order to correctly handle the data.
Conclusion
I'm missing something obvious about promises / async/await. I'm in a coding BootCamp that makes use of Inquirer repeatedly, and I get stuck in the same place every time. Please send help, or at least caffeine.