Reputation: 39
I am trying to write a simple check()
function following this example. The function successfully prints out "True!" but the return value of the function is undefined
when I do console.log(submitModels.verifyOrganizationString(formInputs.organizationString));
. How can I get the function to return true
and false
?
Right now the function only returns "Invalid organization string"
even when the string is valid.
I am thinking this result has to do with the pg-promise
library, but am not sure.
In the file submit.js
, I have:
function verifyOrganizationString(organizationString) {
db.one("select * from organizations where organization_string=$1", [organizationString])
.then(data => {
console.log("True!");
return true;
})
.catch(error => {
console.log("False!");
return false;
});
}
module.exports = {
verifyOrganizationString,
};
In another file, I have
const submitModels = require('../models/submit.js');
function proccessSubmission(req, res) {
var formInputs = req.body;
console.log(submitModels.verifyOrganizationString(formInputs.organizationString));
if (submitModels.verifyOrganizationString(formInputs.organizationString)) {
submitModels.insertIntoDatabase(formInputs);
res.redirect('/');
} else {
res.send("Invalid organization string");
}
}
Upvotes: 0
Views: 364
Reputation: 25890
Your problem is due to both invalid use of promises and bad use of pg-promise.
If you want the function to return true
/false
depending on whether a record is found, change the function to this:
function verifyOrganizationString(organizationString) {
return db.oneOrNone("select * from organizations where organization_string = $1",
organizationString, a => !!a);
}
Then you can use it as one would a regular promise:
verifyOrganizationString('bla-bla')
.then(data => {
// data = true/false
})
.catch(error => {
// error
});
See also: SELECT ⇒ INSERT examples.
Upvotes: 2
Reputation: 875
The reason you're getting undefined is because 'verifyOrganizationString' doesn't actually return anything. You need to return the promise created by your db.one chain.
Although the method will still not return true or false in that case but the Boolean wrapped in another promise so that you can chain the result of your verify function the same way you did with the result of db.one.
Upvotes: 2