Reputation: 212
I'm working in some existing NodeJS code with Core and CoreTest as two of the functions. CoreTest runs a query and stores the selected rows in a variable called CoreSQL. Core is also running some queries, however it requires part of CoreSQL as a parameter for one of the queries.
I think I'm calling CoreTest incorrectly
module.exports = {
CoreTest: (req, res) => {
return new Promise((resolve, reject) => {
const core = db.format.escape(req.query.q);
const coreSQL = `query with parameter = ${core}`;
returnData(coreSQL, resolve, reject);
resolve(coreSQL);
})
},
Core: (req, res) => {
return new Promise((resolve, reject) => {
if (req.query.q.length > 0) {
var core = module.exports.CoreTest(req, res);
}
else
{
reject("PROBLEMS")
}
const coreSQLceDevID = `query where parameter like ${core}`
const coreSQLpID = `query where parameter like ${coreSQLceDevID})`
const coreSQL = `query where parameter like ${coreSQLpID}`
returnDataB(coreSQL, resolve, reject);
})
}
}
The return data functions run the SQL query and looks as follows:
const returnData = (sql, resolve, reject) => {
db.query(sql, (err, result) => {
if (err)
reject(err)
else
resolve(result)
})
}
I'm getting the following error:
error: Unhandled rejection!
Reason:TypeError: Cannot read property 'q' of undefined,
Promise: [object Promise]
Although when I use breakpoints to check the value of q, its not undefined, so it must be an issue with how CoreTest is being called.
Upvotes: 1
Views: 156
Reputation: 664547
Two problems:
in CoreTest
, you are calling both returnData
and resolve
. Drop the immediate resolve()
call, returnData
will do that later. (Btw, I'd recommend renaming that to runQuery
or so).
CoreTest(req, res) {
return new Promise((resolve, reject) => {
const core = db.format.escape(req.query.q);
const coreSQL = `query with parameter = ${core}`;
returnData(coreSQL, resolve, reject);
})
}
in Core
, you seem to expect CoreTest()
to return a value synchronously. It can't do that, it returns a promise. You will need to chain the rest of your code to that with then
or await
. Also you should keep the new Promise
wrapper minimal:
Core(req, res) {
if (req.query.q.length == 0) {
return Promise.reject("PROBLEMS");
}
return module.exports.CoreTest(req, res).then(core => {
// ^^^^^
return new Promise((resolve, reject) => {
const coreSQLceDevID = `query where parameter like ${core}`
const coreSQLpID = `query where parameter like ${coreSQLceDevID})`
const coreSQL = `query where parameter like ${coreSQLpID}`
returnDataB(coreSQL, resolve, reject);
});
});
}
Upvotes: 2