0
\$\begingroup\$

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);
 }
 })();
});
asked Jul 25, 2017 at 11:58
\$\endgroup\$
1

1 Answer 1

4
\$\begingroup\$

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
\$\endgroup\$
2
  • \$\begingroup\$ Thanks for your input. I really like the 'Wes Bos' version, especially its readability. \$\endgroup\$ Commented Jul 25, 2017 at 18:16
  • \$\begingroup\$ He has a great course on learning Node, if you're interested: learnnode.com \$\endgroup\$ Commented Jul 26, 2017 at 1:10

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.