I am developing an Express nodeJS web app and am trying to increase my knowledge of asynchronous programming and how to access the data that I need properly.
I have two callback functions which query an SQL database. My functions are declared like so:
function CustomerList(callback) {
const db = require('../db');
db.query('SELECT * FROM users WHERE role = (?)', ['User'], (error, results, fields) => {
if (error) throw error;
callback(results);
});
}
function AdminList(callback) {
const db = require('../db');
db.query('SELECT * FROM admins WHERE role = (?)', ['Moderator'], (error, results, fields) => {
if (error) throw error;
callback(results);
});
}
I use the data retrieved from both callbacks and send it to my view engine template to be displayed in the browser like so:
CustomerList((userData) => {
AdminList((adminData) => {
res.render('adminhome', {
title: 'Admin - Home',
results: 'test',
customers: userData,
admins: adminData
});
});
This works as expected and I can manipulate the data however I please on my view template. But... This seems... 'clunky', and I feel like this method I am using is going to cause me trouble in the future if I create additional functions to retrieve more data, and then keep nesting additional callbacks to pass the data to my view template.
Essentially, I am struggling to find a suitable approach to retrieve the UserData results and AdminData results and pass them to my res.render API call.
What are better alternatives to my current approach?
Promise.allor leverageasync/await.