3

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.

Shadow
  • 33,525
  • 10
  • 51
  • 64
tritomit
  • 159
  • 11
  • you can simply move `res.send` to the "correct data" part. – technophyle Oct 06 '22 at 09:51
  • and how can I bind the incoming data to the `customers` variable? Even if I move `res.send` to the `correct data` part, outside of this I still cannot use the data received. – tritomit Oct 06 '22 at 10:05

1 Answers1

1

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}.`);
    }
}
JStw
  • 1,155
  • 11
  • 20
  • You were right, the data was not ready thus the `undefined`. I've changed everything to async/await and now it's working properly. Thanks – tritomit Oct 07 '22 at 11:25