在Node.js应用中,异步中间件的性能调优是提升整体系统响应速度的关键环节。本文将通过对比传统回调方式与现代Promise/async-await的中间件实现,展示实际性能差异。
首先,让我们创建一个简单的用户认证中间件进行对比测试。传统回调方式:
const express = require('express');
const app = express();
// 传统回调方式中间件
function authCallbackMiddleware(req, res, next) {
// 模拟异步数据库查询
setTimeout(() => {
const isValid = req.headers.authorization === 'Bearer token123';
if (isValid) {
req.user = { id: 1, name: 'John' };
next();
} else {
res.status(401).json({ error: 'Unauthorized' });
}
}, 10);
}
app.use('/api', authCallbackMiddleware);
使用Promise的中间件实现:
// Promise方式中间件
function authPromiseMiddleware(req, res, next) {
const checkAuth = new Promise((resolve, reject) => {
setTimeout(() => {
const isValid = req.headers.authorization === 'Bearer token123';
if (isValid) {
resolve({ id: 1, name: 'John' });
} else {
reject(new Error('Unauthorized'));
}
}, 10);
});
checkAuth
.then(user => {
req.user = user;
next();
})
.catch(err => {
res.status(401).json({ error: err.message });
});
}
app.use('/api', authPromiseMiddleware);
最佳实践的async-await中间件:
// async-await方式中间件
async function authAsyncMiddleware(req, res, next) {
try {
// 模拟异步操作
await new Promise(resolve => setTimeout(resolve, 10));
const isValid = req.headers.authorization === 'Bearer token123';
if (isValid) {
req.user = { id: 1, name: 'John' };
next();
} else {
throw new Error('Unauthorized');
}
} catch (error) {
res.status(401).json({ error: error.message });
}
}
app.use('/api', authAsyncMiddleware);
性能测试代码:
const axios = require('axios');
const { performance } = require('perf_hooks');
async function benchmark() {
const startTime = performance.now();
// 并发请求测试
const promises = Array(100).fill().map(() =>
axios.get('http://localhost:3000/api/test')
);
await Promise.all(promises);
const endTime = performance.now();
console.log(`总耗时: ${endTime - startTime}ms`);
}
benchmark();
通过对比可以看出,async-await方式在代码可读性和错误处理方面具有明显优势。建议在实际项目中优先使用async-await语法来编写异步中间件,同时配合Promise进行性能优化。

讨论