I am trying to use NodeJS require syntax with an asynchronous database query. I would like the program to wait for the query to complete before it moves on to the next require as some information returned from the database is passed as a parameter to the next require.
Here is my code:
const dealership = require('../models/getDealershipById.js')(id);
const dealershipLeads = require('../models/getLeadsByDealershipId.js')(dealership.id);
const dealershipStaff = require('../models/getStaffByDealershipId.js')(dealership.id);
return [dealership, dealershipLeads, dealershipStaff];
I have tried wrapping this in an anonymous async function but this did not work. Does anyone know how to do this?
Here is my module code:
module.exports = function(id) {
const pool = require('../loaders/pool.js')();
pool.query('SELECT * FROM dealerships WHERE id = \'' + id + '\';', (err,
res)
=> {
if(err) console.error(err.stack);
return res.rows[0];
});
};
As I understand you have wrapped your exported function with async
and await
:
module.exports = function(id) {
return new Promise((resolve, reject) => {
const pool = require('../loaders/pool.js')();
pool.query(
"SELECT * FROM dealerships WHERE id = '" + id + "';",
(err, res) => {
if (err) {
console.error(err.stack);
reject(err);
}
else {
resolve(res.rows[0]);
}
}
);
});
};
So now just use the async
and await
in the calling code:
async function getData() {
const dealership = await require('../models/getDealershipById.js')(id);
const dealershipLeads = await require('../models/getLeadsByDealershipId.js')(dealership.id);
const dealershipStaff = await require('../models/getStaffByDealershipId.js')(dealership.id);
}
getData()
Important: as a side note, avoid "SELECT * FROM dealerships WHERE id = '" + id + "';"
as this is a real bad security antipattern, if the id
is not sanitized correctly it could very easily allow SQL code injection. Use something like pool.query("SELECT * FROM dealerships WHERE id = ?", [id], ...)
if your driver allows it, or replace it with a driver or wrapper that does.