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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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