Express.js Async Await Handling
Many tasks in an Express app take time. A database query, a file read, and an outside API call all finish later, not instantly. JavaScript offers three styles to handle waiting work: callbacks, promises, and async with await. Async and await give the cleanest style. The code reads from top to bottom, like ordinary steps, while the server stays free to serve other users.
The Coffee Shop Analogy
A barista takes an order and starts the espresso machine. The barista does not stare at the machine. The next customer gets served while the coffee brews. A ready signal calls the barista back. The await keyword plays the role of that ready signal. The function pauses at that line, and the server keeps working elsewhere.
Three Styles Compared
| Style | Reading Experience |
|---|---|
| Callbacks | Functions nest inside functions and form deep pyramids |
| Promises | Chained then calls read in a line but grow long |
| Async and await | Code reads like plain top-to-bottom steps |
Flow Diagram
Request arrives
|
v
async handler starts
|
v
await User.findById(id) ---- server serves other requests meanwhile
|
v
Database answers
|
v
Handler continues and sends the response
A Route With async and await
Mark the handler with the async keyword. Place await before any call that returns a promise.
app.get('/users/:id', async (req, res) => {
const user = await User.findById(req.params.id);
if (!user) {
return res.status(404).json({ error: 'User not found' });
}
res.json(user);
});Handle Errors With try and catch
A failed promise throws an error at the await line. Wrap the steps in try and catch, and pass the error to the Express error handler through next.
app.get('/orders/:id', async (req, res, next) => {
try {
const order = await Order.findById(req.params.id);
res.json(order);
} catch (err) {
next(err);
}
});Remove Repeated try and catch
Writing try and catch in every route creates noise. A small wrapper function catches errors for any async handler.
const asyncHandler = (fn) => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.get('/products', asyncHandler(async (req, res) => {
const products = await Product.find();
res.json(products);
}));
app.use((err, req, res, next) => {
res.status(500).json({ error: err.message });
});Express 5 includes this behavior by default. It forwards rejected promises from async handlers to the error handler automatically. Express 4 projects still need the wrapper.
Run Tasks in Parallel
Two awaits in a row run one after the other. Independent tasks finish sooner when they run together with Promise.all.
app.get('/dashboard', async (req, res) => {
const [users, orders, products] = await Promise.all([
User.countDocuments(),
Order.countDocuments(),
Product.countDocuments()
]);
res.json({ users, orders, products });
});
Sequential: [users 100ms][orders 100ms][products 100ms] = 300ms
Parallel: [users 100ms]
[orders 100ms]
[products 100ms] = about 100ms
Common Mistakes
Forgetting await
A call without await returns a pending promise instead of the data. The response then shows an empty object.
Using await Outside an async Function
The await keyword works only inside async functions, and at the top level of ES modules.
Sending Two Responses
Calling res.json twice crashes the route. Add return before an early response so the function stops there.
Blocking the Server
Heavy loops and synchronous file calls such as readFileSync freeze every user. Choose the asynchronous version of each call.
Best Practices
- Mark every handler that awaits something with async.
- Send errors to one central error handler.
- Use Promise.all for independent tasks.
- Prefer the promise versions of Node.js modules, such as fs/promises.
