anti-pattern
This is the explicit promise construction anti-pattern -
let personInfo = new Promise((success,reject)=>{
Person.find({ Group: 'pre'})
.then((par) => {
if (par.length > 0) {
success(par);
} else {
reject("Error");
}
})
.catch((err) => { console.log(err); });
});
You can replace it with -
let personInfo = Person.find({ Group: 'pre'})
.then((par) => {
if (par.length > 0) {
return par
} else {
throw Error("Error: empty par");
}
})
.catch(console.error) // <- don't catch here
And you should probably leave the .catch
off and expect the caller to handle error handling. The .catch
handler below would never trigger if the error is catch
'd before
exports.Ac = (req, res, next) => {
let person = new require('./general');
person.personInfo
.then((par) => {
res.render('/myPage/Account', { // no "return" needed
title: 'Account',
group: par
});
})
.catch((err) => { console.log(err); }); // <- keep catch here
}
The reason it is only happening once, is because Promises can only be resolved or rejected once. You'll have to replace personInfo
with a function -
const Person = require('../models/person');
const fetchPersonInfo = () =>
Person.find({ Group: 'pre'})
.then((par) => {
if (par.length > 0) {
return par
} else {
throw Error("Error: empty par");
}
})
});
module.exports.fetchPersonInfo = fetchPersonInfo;
async await
You might also want to consider reading up on async
/await
as they make your life a lot better
const Person = require('../models/person');
async function fetchPersonInfo () { // <- async
const par = await Person.find({ Group: 'pre'}) // <- await
if (par.length > 0)
return par;
else
throw Error("Error: empty par");
});
module.exports.fetchPersonInfo = fetchPersonInfo;
const { fetchPersonInfo } = new require('./general'); // <- top-level import
exports.Ac = async (req, res, next) => { // <- async
try {
const par = await fetchPersonInfo() // <- await
res.render('/myPage/Account', {
title: 'Account',
group: par
});
} catch (err) {
console.log(err)
}
}