I'm a Node.js student, and I'm writing a brief example. The get on /org works as expected.
With the get on /orgg I tried to segregate the server "fetch the data" logic from the controller. However, the getRowsAsync() immediately returns a Promise.
This "put the await in express.get()" isn't good for hiding logic. If my biz logic needed some sequential Promises then the biz logic would have to bubble into the controller.
How can I do the equivalent to calling "doBizLogic()" in the controller, hiding my awaits, and having the controller wait for the logic to complete? Must I pass a callback function to the biz logic to make this scheme work?
Here is my index.js. I omit database.js, but I borrowed it from https://mhagemann.medium.com/create-a-mysql-database-middleware-with-node-js-8-and-async-await-6984a09d49f4
const express = require("express");
const urlPort = 3000;
let app = express();
let mysql = require("mysql2");
let pool = require("./database");
app.listen(urlPort, () => {
console.log("Server is running at port " + urlPort);
});
app.get("/", (req, res) => {
res.send("This app responds to /org and /org/:id only.");
});
app.get("/org", async (req, res) => {
let rows = await getRows("select * from org");
// the log always prints a JSON array.
console.log("in app.get for /org, rows: ", rows);
res.send(rows);
});
app.get("/orgg", (req, res) => {
let rows = getRowsAsync();
// the log() prints immediately prints a Promise.
console.log("in app.get for /orgg, rows: ", rows);
res.send(rows);
});
function getRows(sql, params = []) {
let rows = pool.query(sql, params);
// the log() prints a Promise.
console.log("in getRows, rows: ", rows); // returns
return rows;
}
async function getRowsAsync() {
let rows = await getRows("select * from org");
// the log() prints a JSON array, once it is finally called.
console.log("in getRowsAsync, rows: ", rows);
return rows;
}