re: Using Async/await in Express VIEW POST

FULL DISCUSSION
 

some things to note here:

  • I remember seeing in a article that try / catch blocks are not minified, haven't tested it out yet, but it's something to be careful about.
  • While you can use try / catch blocks, note that:
    1. The async function returns a Promise
    2. You usually would have the request handler declared in a controller file and have services functions handle the operations.
    3. Promises can handle errors.

So you could also do things like this:



// user/services/user.service.getAll.ts
export default async function getAllUsers(filter: string, page: number): Promixe<IUser[]> {
   //...
}

// user/controllers/user.get.controller.ts
/*
* controller documentation...
*/
async function userGetController(req, res, next): Promise<void> {
   let { filter, page } = req.query;
   filter = filter || '';
   page = parseInt(page) || 1;
   const users = await getAllUsers(filter, page)
   .then(users => res.json(users))
   .catch(function getAllUsersControllerError(e) {
     let status = 500;
     let errorObject: IApiError = {
       //...
     }

     const returnedApiError = !!e.status;

     if (returnedApiError) {
       status = e.status;
       errorObject = e;
     }

     res.status(status).json(errorObject);
   });
}

// user/user.router.ts
app.get('/users', userGetController);

// or if you want to be even more safe

app.get('/users', function userGetRoute(req, res, next): Promise<void> {
  return userGetController(req, res, next).catch(e => {
     // do something...
  });
});
code of conduct - report abuse