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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.