I can't accomplish async and await in order to populate array and then show the end result.
When I execute the code, firstly there is an empty array. When I go "refresh", then data is populated.
Obviously async. But I don't know how to write the code
The similar problem is described here
https://community.apigee.com/questions/49199/nodejs-cache-retrieve-data-and-push-to-array.html
My code so far
const express = require('express');
const router = express.Router();
const db = require('../../config');
var async = require('async');
function readDb(nameOfTableInDb, someArray) {
// reuse a conneciton to db
db.getConnection(function (err, conn) {
if (err) {
res.json({ "code": 100, "status": "Error in connection DB..." });
return;
}
let qry = "";
switch (nameOfTableInDb) {
case "tblcategories": {
qry = "SELECT DISTINCT c.catName, (select COUNT(*) from tblPostCatMap as pp where pp.idcat = c.idcategorie) as summeCat from " + nameOfTableInDb + " as c order by c.catName asc";
break;
}
case "tblsubcat": {
qry = "SELECT DISTINCT c.subCatName, (select COUNT(*) from tblPostCatMap as pp where pp.idSubCat = c.idSubCat) as summeSubcat from " + nameOfTableInDb + " as c order by c.subCatName asc";
break;
}
}
conn.query(qry, function (error, rows) {
if (error) {
throw error;
}
// add results from DB to someArray array
someArray.push(rows);
});
conn.release();
});
return someArray;
}
router.get('/', function (req, res, next) {
var someArray = [];
var run = async() => {
const data = await readDb("tblcategories", someArray);
const data = await readDb("tblsubcat", someArray);
console.log("async result:\n" + data);
}
run();
});