\$\begingroup\$
\$\endgroup\$
1
Would anyone be so kind to assist me if I’m ‘cooking’ async/await a right way?
I attend to return an express response once promise to DB resolves.
router.get('/', (req, res, next) => {
(async function() {
try {
const cases = await db.collections.cases.stats();
return res.render('index', {
title: 'Welcome',
totalDBRecords: cases.count,
});
}
catch (e) {
console.error(e);
next(e);
}
})();
});
-
1\$\begingroup\$ The site standard is for the title to simply state the task accomplished by the code. Please see How to get the best value out of Code Review - Asking Questions for guidance on writing good question titles. \$\endgroup\$BCdotWEB– BCdotWEB2017年07月25日 13:27:51 +00:00Commented Jul 25, 2017 at 13:27
1 Answer 1
\$\begingroup\$
\$\endgroup\$
2
I don't think you need to wrap this in an IFFE. You can simply write the async function as follows:
router.get('/', async (res, req, next) => {
try {
const cases = await db.collections.cases.stats();
res.render('index', {
title: 'Welcome',
totalDBRecords: cases.count,
});
} catch(err) {
console.log(err);
next(err);
}
});
That should work. I also like the way Wes Bos wraps his functions in an error handler, like so (eliminates having to use try/catch).
const catchErr = (fn) => {
return function(res, req, next) {
fn(req, res, next).catch(next);
}
};
const home = async (res, req, next) => {
const cases = await db.collections.cases.stats();
res.render('index', {
title: 'Welcome',
totalDBRecords: cases.count,
});
};
router.get('/', catchErr(home));
answered Jul 25, 2017 at 15:55
-
\$\begingroup\$ Thanks for your input. I really like the 'Wes Bos' version, especially its readability. \$\endgroup\$Coderbit– Coderbit2017年07月25日 18:16:21 +00:00Commented Jul 25, 2017 at 18:16
-
\$\begingroup\$ He has a great course on learning Node, if you're interested: learnnode.com \$\endgroup\$Calvin Koepke– Calvin Koepke2017年07月26日 01:10:46 +00:00Commented Jul 26, 2017 at 1:10
lang-js