I have a function that makes a database query, then needs to return the result.
The query is to a mysql database, using Node.js, the result is then returned to an Inquirer (NPM module) prompt.
If this was a front end issue, I would use the built in promises of jquery: (example). $.ajax.done(). However the mysql NPM package doesn't have built in promises for the query() method.
// OPTION 1, wait for query to complete before returning choicesArray (this example returns an empty array)
choices() {
let choicesArray = [];
connection.query(`SELECT * FROM products`, (err, res)=>{
for (item of res) {
choicesArray.push(`${item.product} | ${item.price}`);
};
});
// wait here for query to complete
return choicesArray;
}
// OPTION 2, change the syntax to take advantage of the query callback, something more like below (this example does not return the choicesArray all the way to the enclosing function)
choices() {
connection.query(`SELECT * FROM products`, (err, res)=>{
let choicesArray = [];
for (item of res) {
choicesArray.push(`${item.product} | ${item.price}`);
};
return choicesArray;
});
} // (node:3877) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Error: You must provide a `choices` parameter