Home > other >  Issue while trying to call an existing route from within another route in Express JS project
Issue while trying to call an existing route from within another route in Express JS project

Time:10-07

In an Express JS connected to a mySQL db, I am trying to get some data of an already defined route/ query:

// customers.model.js
CUSTOMERS.getAll = (result) => {
    let query = "SELECT * FROM customers"

    sql.query(query, (err, res) => {
        if (err) {
            console.log("error: ", err)
            result(null, err)
            return
        }

        result(null, res)
    })
}

// customers.controller.js

// GET customers is a standalone route and should output all the customers when called.

const CUSTOMERS = require("../models/customers.model.js")

exports.findAll = (req, res) => {
    return CUSTOMERS.getAll((err, data) => {
        if (err)
            res.status(500).send({
                message: err.message ||
                    "Some error occurred while retrieving customers...",
            })
        else res.send(data)
    })
}

In payments.controller.js I would firstly like to get all users so I can do something with the data:

// payments.controller.js

// GET payments is also a standalone route and should get the customers,
// do something with the data and output a calculation with the help of this data

const CUSTOMERS = require("../models/customers.model.js")

exports.calculateAll = (req, res) => {

    const customers = CUSTOMERS.getAll((err, data) => {
        console.log('this always has correct data', data)
        if (err) return err
        else return data
    })

    console.log('this is always undefined', customers)

    ...
    
    res.send(whatEverCalculatedData)...
}

But that data here is always undefined. What am I doing wrong in the above, and what's the correct way to call this route inside another route?

I know it has similarities with this question but I couldn't sort it out for my particular example.

CodePudding user response:

It's due to your call which is asynchronous. You must wait your data being ready before rendering the results.

Maybe you could to use Promises or async/await statements.

For example:

CUSTOMERS.getAll = async () => {
    const query = "SELECT * FROM customers";

    try {
      return await sql.query(query);
    } catch (e) {
       console.log(`An error occurred while fetching customers: ${e.message}.`);
       return null;
    }
}



exports.calculateAll = async (req, res) => {
    try {
        const data = await CUSTOMERS.getAll();
        res.send(whatEverCalculatedData);
    } catch (e) {
       res.send(`Something went wront: ${e.message}.`);
    }
}
  • Related