How to write async route handlers — Intermediate
Mark controller functions async and await service/Knex calls. Always forward failures with next(err) so the error middleware can respond.
Learn: Async handlers must forward rejections with `next(err)`—otherwise Express may not invoke your error middleware. Wrapping async functions or using a small `asyncHandler` utility removes repetitive try/catch blocks.
Supplementary examples
asyncHandler wrapper
function asyncHandler(fn) {
return (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
}
router.get("/", asyncHandler(async (req, res) => {
const rows = await service.list();
res.json({ data: rows });
}));Course example
async function create(req, res, next) {
try {
const created = await service.create(req.body);
res.status(201).json({ data: created });
} catch (err) {
next(err);
}
}
Additional references & examples
- MDN: async/await
JavaScript async functions used in route handlers.
- Knex.js documentation
Query builder, migrations, seeds, and connection configuration.