0

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?

1
  • Use Promise.all or leverage async/await. Commented Jul 16, 2018 at 14:36

1 Answer 1

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

This does look like the solution to my problem, however, I am getting: "TypeError: Cannot read property 'typeCast' of undefined". I am researching this error now, but any ideas?
After researching, i changed my db.js file to use a connectionPool instead of just a connection, this allowed your code snippet to work perfectly. Thank you!! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.