I have recently started learning node.js and for that purpose started converting one of my php projects.
I am trying to understand how async and await works, but cannot seem to find a solution on my own and would appreciate some help.
I have following function
exports.getTypes = async (req, res) => {
var categories = [];
pool.query('call livestockGetTypeAll()', [],
await function(err, results, fields) {
if (err) throw err;
//return res.json(results[0]);
categories = JSON.parse(JSON.stringify(results[0]));
for(let i = 0; i < categories.length; i++){
req.body.id = categories[i].id;
categories[i].sub_items = exports.getSubTypes(req, res);
}
return res.json(categories);
}
);
};
This function is supposed to call another one and populate sub_items
exports.getSubTypes = async (req, res) => {
pool.query('call livestockGetSubTypeAll(?)',
[
req.body.id
],
await function(err, results, fields) {
if (err) throw err;
//return res.json(results[0]);
return results[0];
}
);
};
But it seem to return categories from the first function without waiting for any response to populate sub_items.
I would really appreciate help on this one.