Reputation: 301
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?
Upvotes: 0
Views: 198
Reputation: 10071
Yes, it'll create callback hell if you call multiple callbacks inside the callback, use promises(async/await)
const util = require('util');
const db = require('../db');
const query = util.promisify(db.query);
const getData = async () => {
try {
const CustomerList = await query('SELECT * FROM users WHERE role = (?)', ['User']);
const AdminList = await query('SELECT * FROM admins WHERE role = (?)', ['Moderator']);
// OR Promise.all
const [CustomerList, AdminList] = await Promise.all([
query('SELECT * FROM users WHERE role = (?)', ['User']),
query('SELECT * FROM admins WHERE role = (?)', ['Moderator'])
]);
} catch (error) {
console.log(error);
}
}
Upvotes: 1