Performance: Async middleware wrapper
This concept affects server response time and error handling efficiency, impacting how quickly the server can respond to requests without blocking.
const asyncWrapper = fn => (req, res, next) => {
Promise.resolve(fn(req, res, next)).catch(next);
};
app.use(asyncWrapper(async (req, res, next) => {
const data = await someAsyncFunction();
res.send(data);
}));app.use(async (req, res, next) => { const data = await someAsyncFunction(); res.send(data); // No try/catch or error forwarding });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Async middleware without wrapper | N/A | N/A | N/A | [X] Bad |
| Async middleware with wrapper | N/A | N/A | N/A | [OK] Good |
async middleware wrapper in Express?/data?
const express = require('express');
const app = express();
const wrap = fn => (req, res, next) => fn(req, res, next).catch(next);
app.get('/data', wrap(async (req, res) => {
const data = await Promise.resolve('Hello World');
res.send(data);
}));
app.use((err, req, res, next) => {
res.status(500).send('Error caught');
});
app.listen(3000);const wrap = fn => (req, res, next) => {
try {
fn(req, res, next);
} catch (err) {
next(err);
}
};Pass the test and this pattern moves unknown