AJAX并发请求处理全解析:从原理到实战技巧与性能优化策略

什么是AJAX及其并发请求的基本概念
AJAX(Asynchronous JavaScript and XML)是一种在无需重新加载整个网页的情况下,能够更新部分网页的技术。它通过在后台与服务器进行少量数据交换,使网页实现异步更新。AJAX的核心是XMLHttpRequest对象(现代开发中也常用Fetch API),它允许JavaScript在不阻塞用户界面的情况下向服务器发送请求并接收响应。
并发请求指的是同时发起多个AJAX请求,而不是一个接一个地顺序执行。在现代Web应用中,经常需要同时从多个数据源获取数据,例如一个电商网站可能需要同时加载产品信息、用户评论和推荐商品。理解并发请求的原理和优化策略对于提升用户体验和应用性能至关重要。
AJAX并发请求的底层原理
浏览器的并发限制
浏览器对同一域名下的并发连接数有严格限制。这个限制因浏览器而异,但通常在6-8个之间。例如,Chrome和Firefox默认限制为6个并发请求。这意味着如果你同时发起10个请求到同一个域名,前6个会立即发送,而后4个需要等待前6个中的某个完成后才能开始。
这种限制是为了防止客户端和服务器过载,确保网络资源合理分配。理解这一限制是优化并发请求的第一步。
HTTP/1.1与HTTP/2的差异
HTTP/1.1使用文本协议,每个TCP连接只能处理一个请求-响应周期,虽然支持持久连接,但并发能力有限。而HTTP/2引入了多路复用技术,允许在单个TCP连接上同时传输多个请求和响应,大大提高了并发效率。
在HTTP/2环境下,浏览器并发限制会放宽,但服务器配置和网络环境仍然会影响实际性能。
实现AJAX并发请求的多种方法
方法一:Promise.all() – 现代推荐方式
// 使用Fetch API和Promise.all实现并发请求
async function fetchMultipleData() {
const urls = [
‘https://api.example.com/products’,
‘https://api.example.com/users’,
‘https://api.example.com/categories’
];

try {
// 同时发起所有请求
const responses = await Promise.all(
urls.map(url => fetch(url))
);

// 等待所有响应完成并解析JSON
const data = await Promise.all(
responses.map(response => response.json())
);

console.log(‘所有数据:’, data);
return data;
} catch (error) {
console.error(‘请求失败:’, error);
// 注意:如果任何一个请求失败,整个Promise.all会立即reject
}
}

// 使用示例
fetchMultipleData().then(data => {
// 处理获取到的数据
updateUI(data);
});
Promise.all()的特点:
所有请求同时发起,最大化并发效率
如果任何一个请求失败,整个操作立即失败
返回结果的顺序与输入数组的顺序一致
适用于需要所有数据都成功获取的场景
方法二:Promise.allSettled() – 容错方案
// 使用Promise.allSettled()处理可能失败的请求
async function fetchWithFallback() {
const endpoints = [
‘https://api.example.com/primary’,
‘https://api.example.com/backup’,
‘https://api.example.com/cache’
];

const results = await Promise.allSettled(
endpoints.map(url =>
fetch(url).then(res => res.json())
)
);

// 处理每个请求的结果
const successfulData = results
.filter(result => result.status === ‘fulfilled’)
.map(result => result.value);

const failedRequests = results
.filter(result => result.status === ‘rejected’)
.map(result => result.reason);

console.log(‘成功:’, successfulData);
console.log(‘失败:’, failedRequests);

return successfulData;
}
Promise.allSettled()的优势:
即使部分请求失败,也会等待所有请求完成
可以获取每个请求的详细状态信息
适用于需要部分数据即可继续的场景
方法三:手动控制并发数量 – 高级技巧
当需要同时发起大量请求时,直接使用Promise.all()可能导致浏览器卡顿或服务器过载。这时需要限制并发数量:
// 限制并发数量的请求处理器
class ConcurrentRequestLimiter {
constructor(maxConcurrent = 3) {
this.maxConcurrent = maxConcurrent;
this.queue = [];
this.activeRequests = 0;
}

// 添加请求到队列
async add(requestFn) {
return new Promise((resolve, reject) => {
this.queue.push({ requestFn, resolve, reject });
this.processQueue();
});
}

// 处理队列中的请求
async processQueue() {
if (this.activeRequests >= this.maxConcurrent || this.queue.length === 0) {
return;
}

const { requestFn, resolve, reject } = this.queue.shift();
this.activeRequests++;

try {
const result = await requestFn();
resolve(result);
} catch (error) {
reject(error);
} finally {
this.activeRequests–;
// 继续处理下一个请求
this.processQueue();
}
}
}

// 使用示例
const limiter = new ConcurrentRequestLimiter(3); // 最多3个并发

// 创建10个请求任务
const requests = Array.from({ length: 10 }, (_, i) =>
() => fetch(`https://api.example.com/data/${i}`).then(res => res.json())
);

// 依次添加到队列
requests.forEach(request => {
limiter.add(request)
.then(data => console.log(‘成功:’, data))
.catch(error => console.error(‘失败:’, error));
});
方法四:使用async/await与for循环实现顺序控制
// 使用async/await实现可控的并发模式
async function controlledConcurrentRequests(urls, batchSize = 3) {
const results = [];

for (let i = 0; i < urls.length; i += batchSize) { // 每批同时发起batchSize个请求 const batch = urls.slice(i, i + batchSize); const batchPromises = batch.map(url =>
fetch(url)
.then(res => res.json())
.catch(error => ({ error, url })) // 捕获错误,不影响其他请求
);

const batchResults = await Promise.all(batchPromises);
results.push(…batchResults);

// 可选:每批之间添加延迟
if (i + batchSize < urls.length) { await new Promise(resolve => setTimeout(resolve, 100));
}
}

return results;
}

// 使用示例
const manyUrls = Array.from({ length: 20 }, (_, i) =>
`https://api.example.com/data/${i}`
);

controlledConcurrentRequests(manyUrls, 5).then(results => {
console.log(‘所有结果:’, results);
});
实战技巧:处理不同场景下的并发请求
场景一:需要部分数据即可展示的页面
// 优先级请求策略:先加载关键数据,再加载次要数据
async function loadPriorityData() {
// 关键数据(必须)
const criticalRequests = [
fetch(‘/api/user/profile’).then(res => res.json()),
fetch(‘/api/dashboard/summary’).then(res => res.json())
];

// 次要数据(可选)
const secondaryRequests = [
fetch(‘/api/notifications’).then(res => res.json()),
fetch(‘/api/recommendations’).then(res => res.json())
];

// 先加载关键数据
const [user, summary] = await Promise.all(criticalRequests);
updateCriticalUI(user, summary);

// 再加载次要数据
try {
const [notifications, recommendations] = await Promise.all(secondaryRequests);
updateSecondaryUI(notifications, recommendations);
} catch (error) {
console.warn(‘次要数据加载失败,不影响主功能’);
}
}
场景二:实时搜索建议(取消重复请求)
// 搜索框的并发请求处理,支持取消
class SearchSuggestions {
constructor() {
this.currentController = null;
this.debounceTimer = null;
}

async getSuggestions(query) {
// 取消之前的请求
if (this.currentController) {
this.currentController.abort();
}

// 创建新的AbortController
this.currentController = new AbortController();

try {
const response = await fetch(
`/api/suggestions?q=${encodeURIComponent(query)}`,
{ signal: this.currentController.signal }
);

const suggestions = await response.json();
this.displaySuggestions(suggestions);
} catch (error) {
if (error.name === ‘AbortError’) {
console.log(‘请求被取消’);
} else {
console.error(‘搜索失败:’, error);
}
}
}

// 防抖函数
onSearchInput(query) {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(() => {
this.getSuggestions(query);
}, 300);
}
}

// 使用示例
const search = new SearchSuggestions();
document.getElementById(‘search’).addEventListener(‘input’, (e) => {
search.onSearchInput(e.target.value);
});
场景三:分页数据加载优化
// 分页数据预加载策略
class PaginationOptimizer {
constructor() {
this.prefetched = new Map();
this.currentPage = 1;
}

// 获取当前页数据
async getCurrentPage(page) {
if (this.prefetched.has(page)) {
return this.prefetched.get(page);
}

const data = await this.fetchPage(page);
return data;
}

// 预加载下一页
async prefetchNextPage(page) {
const nextPage = page + 1;
if (!this.prefetched.has(nextPage)) {
const data = this.fetchPage(nextPage);
this.prefetched.set(nextPage, data);

// 预加载下下页
const nextNextPage = page + 2;
if (nextNextPage <= this.totalPages) { this.fetchPage(nextNextPage).then(data => {
this.prefetched.set(nextNextPage, data);
});
}
}
}

async fetchPage(page) {
const response = await fetch(`/api/items?page=${page}`);
return await response.json();
}
}
性能优化策略
1. 合并请求(Request Batching)
// 将多个请求合并为一个批量请求
class RequestBatcher {
constructor() {
this.batchQueue = [];
this.batchTimer = null;
this.batchSize = 10; // 最多合并10个请求
}

// 添加请求到批处理队列
addToBatch(endpoint, params) {
return new Promise((resolve, reject) => {
this.batchQueue.push({
endpoint,
params,
resolve,
reject
});

// 达到批次大小立即发送
if (this.batchQueue.length >= this.batchSize) {
this.flush();
} else {
// 否则设置延迟发送
this.scheduleFlush();
}
});
}

scheduleFlush() {
if (this.batchTimer) return;

this.batchTimer = setTimeout(() => {
this.flush();
}, 50); // 50ms内收集请求
}

async flush() {
if (this.batchQueue.length === 0) return;

clearTimeout(this.batchTimer);
this.batchTimer = null;

const batch = this.batchQueue.splice(0);

// 构建批量请求体
const batchPayload = batch.map(item => ({
endpoint: item.endpoint,
params: item.params
}));

try {
const response = await fetch(‘/api/batch’, {
method: ‘POST’,
headers: { ‘Content-Type’: ‘application/json’ },
body: JSON.stringify({ requests: batchPayload })
});

const results = await response.json();

// 分发结果
batch.forEach((item, index) => {
if (results[index].success) {
item.resolve(results[index].data);
} else {
item.reject(results[index].error);
}
});
} catch (error) {
// 批处理失败,全部reject
batch.forEach(item => item.reject(error));
}
}
}

// 使用示例
const batcher = new RequestBatcher();

// 多个独立调用会被合并
batcher.addToBatch(‘/api/user’, { id: 1 }).then(data => console.log(data));
batcher.addToBatch(‘/api/user’, { id: 2 }).then(data => console.log(data));
batcher.addToBatch(‘/api/product’, { id: 100 }).then(data => console.log(data));
2. 缓存策略
// 简单的内存缓存实现
class RequestCache {
constructor(ttl = 60000) { // 默认缓存1分钟
this.cache = new Map();
this.ttl = ttl;
}

async get(url, fetchFn) {
const now = Date.now();
const cached = this.cache.get(url);

// 检查缓存是否有效
if (cached && (now – cached.timestamp) < this.ttl) { console.log('使用缓存:', url); return cached.data; } // 重新获取 console.log('重新获取:', url); const data = await fetchFn(); this.cache.set(url, { data, timestamp: now }); return data; } // 清除过期缓存 cleanup() { const now = Date.now(); for (const [url, cached] of this.cache.entries()) { if (now - cached.timestamp > this.ttl) {
this.cache.delete(url);
}
}
}
}

// 使用示例
const cache = new RequestCache(30000); // 30秒缓存

async function getUserData(userId) {
return cache.get(
`/api/user/${userId}`,
() => fetch(`/api/user/${userId}`).then(res => res.json())
);
}
3. 错误处理与重试机制
// 带重试机制的请求函数
async function fetchWithRetry(url, options = {}, maxRetries = 3) {
let lastError;

for (let attempt = 1; attempt <= maxRetries; attempt++) { try { const response = await fetch(url, options); // 检查HTTP状态码 if (!response.ok) { throw new Error(`HTTP ${response.status}: ${response.statusText}`); } return await response.json(); } catch (error) { lastError = error; console.warn(`请求失败 (尝试 ${attempt}/${maxRetries}):`, error.message); // 指数退避策略 if (attempt < maxRetries) { const delay = Math.pow(2, attempt) * 1000; // 2s, 4s, 8s... await new Promise(resolve => setTimeout(resolve, delay));
}
}
}

throw lastError;
}

// 使用示例
fetchWithRetry(‘/api/critical-endpoint’, {}, 3)
.then(data => console.log(‘成功:’, data))
.catch(error => console.error(‘最终失败:’, error));
4. 请求优先级管理
// 优先级队列实现
class PriorityQueue {
constructor() {
this.high = [];
this.medium = [];
this.low = [];
}

add(request, priority = ‘medium’) {
const item = { request, priority };

switch (priority) {
case ‘high’:
this.high.push(item);
break;
case ‘medium’:
this.medium.push(item);
break;
case ‘low’:
this.low.push(item);
break;
}
}

// 按优先级顺序执行
async executeAll() {
const results = [];

// 高优先级
for (const item of this.high) {
results.push(await item.request());
}

// 中优先级
for (const item of this.medium) {
results.push(await item.request());
}

// 低优先级
for (const item of this.low) {
results.push(await item.request());
}

return results;
}
}

// 使用示例
const pq = new PriorityQueue();

pq.add(() => fetch(‘/api/user/profile’).then(r => r.json()), ‘high’);
pq.add(() => fetch(‘/api/notifications’).then(r => r.json()), ‘medium’);
pq.add(() => fetch(‘/api/analytics’).then(r => r.json()), ‘low’);

pq.executeAll().then(results => {
console.log(‘按优先级完成:’, results);
});
现代替代方案:Axios与Fetch API对比
Axios的并发处理
// Axios的并发请求处理
import axios from ‘axios’;

// 创建实例
const api = axios.create({
baseURL: ‘https://api.example.com’,
timeout: 10000,
});

// 并发请求
async function concurrentAxiosRequests() {
try {
const [user, posts, comments] = await Promise.all([
api.get(‘/user/1’),
api.get(‘/posts?userId=1’),
api.get(‘/comments?postId=1’)
]);

return { user: user.data, posts: posts.data, comments: comments.data };
} catch (error) {
// Axios错误处理
if (axios.isCancel(error)) {
console.log(‘请求被取消:’, error.message);
} else if (error.code === ‘ECONNABORTED’) {
console.log(‘请求超时’);
} else {
console.error(‘请求失败:’, error.message);
}
}
}

// 取消请求
const source = axios.CancelToken.source();

api.get(‘/api/data’, {
cancelToken: source.token
}).catch(error => {
if (axios.isCancel(error)) {
console.log(‘请求被取消’);
}
});

// 取消请求
source.cancel(‘用户取消操作’);
Fetch API vs Axios对比
特性
Fetch API
Axios
浏览器支持
现代浏览器
所有浏览器(包括IE11)
取消请求
AbortController
CancelToken
错误处理
需手动检查response.ok
自动处理HTTP错误
响应解析
需手动调用.json()等
自动JSON解析
拦截器
无
支持请求/响应拦截器
上传进度
需使用XMLHttpRequest
内置支持
体积
浏览器原生
需要安装(约13KB)
性能监控与调试技巧
1. 使用Performance API监控请求性能
// 监控AJAX请求性能
class PerformanceMonitor {
constructor() {
this.metrics = [];
}

async monitoredFetch(url, options = {}) {
const startTime = performance.now();
const metricName = `fetch_${url}`;

try {
const response = await fetch(url, options);
const fetchTime = performance.now() – startTime;

// 记录性能指标
this.metrics.push({
url,
duration: fetchTime,
status: response.status,
timestamp: new Date().toISOString()
});

// 使用Performance Observer记录
if (‘PerformanceObserver’ in window) {
performance.mark(`${metricName}_start`);
performance.mark(`${metricName}_end`);
performance.measure(
metricName,
`${metricName}_start`,
`${metricName}_end`
);
}

return response;
} catch (error) {
const endTime = performance.now();
this.metrics.push({
url,
duration: endTime – startTime,
error: error.message,
timestamp: new Date().toISOString()
});
throw error;
}
}

getReport() {
return {
totalRequests: this.metrics.length,
averageDuration: this.metrics.reduce((sum, m) => sum + m.duration, 0) / this.metrics.length,
slowest: this.metrics.reduce((max, m) => m.duration > max.duration ? m : max, { duration: 0 }),
metrics: this.metrics
};
}
}

// 使用示例
const monitor = new PerformanceMonitor();

// 替换原来的fetch调用
monitor.monitoredFetch(‘/api/data’)
.then(res => res.json())
.then(data => {
console.log(‘请求完成’);
console.log(‘性能报告:’, monitor.getReport());
});
2. 使用Chrome DevTools调试并发请求
在Chrome DevTools的Network面板中:
查看”Waterfall”列可以观察请求的时序关系
红色三角形表示请求被阻止
绿色三角形表示请求被缓存
右键点击请求可以”Replay XHR”重新发送
使用”Preserve log”在页面跳转时保留请求记录
3. 模拟慢网络测试
// 在代码中模拟慢网络(仅用于测试)
async function simulateSlowNetwork(request, delay = 2000) {
await new Promise(resolve => setTimeout(resolve, delay));
return request();
}

// 测试并发请求在慢网络下的表现
async function testSlowNetwork() {
const requests = [
simulateSlowNetwork(() => fetch(‘/api/1’), 1000),
simulateSlowNetwork(() => fetch(‘/api/2’), 1500),
simulateSlowNetwork(() => fetch(‘/api/3’), 800)
];

const startTime = performance.now();
const results = await Promise.all(requests);
const totalTime = performance.now() – startTime;

console.log(`总耗时: ${totalTime}ms`); // 应该是1500ms左右(最慢的请求)
}
常见问题与解决方案
问题1:浏览器并发限制导致请求排队
症状
:大量请求时,部分请求延迟很高。
解决方案
:
使用HTTP/2(自动解决)
域名分片(Domain Sharding):将请求分散到不同子域名
合并请求减少总数
使用优先级队列优先处理关键请求
问题2:内存泄漏
症状
:长时间运行的应用内存持续增长。
解决方案
:
// 清理未完成的请求
class RequestManager {
constructor() {
this.pendingRequests = new Set();
}

async fetchWithCleanup(url, options = {}) {
const controller = new AbortController();
const requestPromise = fetch(url, { …options, signal: controller.signal });

// 添加到pending集合
this.pendingRequests.add(controller);

try {
const result = await requestPromise;
return result;
} finally {
// 无论成功失败都清理
this.pendingRequests.delete(controller);
}
}

// 页面卸载时取消所有pending请求
cleanupAll() {
this.pendingRequests.forEach(controller => controller.abort());
this.pendingRequests.clear();
}
}

// 页面卸载时清理
window.addEventListener(‘beforeunload’, () => {
requestManager.cleanupAll();
});
问题3:请求竞态条件(Race Condition)
症状
:快速连续操作时,返回的数据顺序混乱。
解决方案
:
// 使用AbortController取消旧请求
class RaceConditionPreventer {
constructor() {
this.controller = null;
}

async fetch(url) {
// 取消之前的请求
if (this.controller) {
this.controller.abort();
}

this.controller = new AbortController();

try {
const response = await fetch(url, {
signal: this.controller.signal
});

return await response.json();
} catch (error) {
if (error.name === ‘AbortError’) {
// 请求被取消,忽略错误
return null;
}
throw error;
}
}
}
总结与最佳实践
核心原则
理解浏览器限制
:知道并发限制,合理规划请求策略
优先级管理
:区分关键数据和次要数据
错误处理
:为每个请求添加适当的错误处理
取消机制
:实现请求取消,避免内存泄漏和竞态条件
性能监控
:持续监控请求性能,及时发现瓶颈
推荐的并发请求模式
// 生产环境推荐的完整模式
class ProductionRequestManager {
constructor(options = {}) {
this.maxConcurrent = options.maxConcurrent || 6;
this.timeout = options.timeout || 10000;
this.retryCount = options.retryCount || 2;
this.cache = new Map();
this.activeRequests = 0;
this.queue = [];
}

async request(url, options = {}) {
// 1. 检查缓存
const cacheKey = JSON.stringify({ url, options });
if (this.cache.has(cacheKey)) {
const cached = this.cache.get(cacheKey);
if (Date.now() – cached.timestamp < (options.ttl || 60000)) { return cached.data; } } // 2. 加入队列等待执行 return new Promise((resolve, reject) => {
this.queue.push({ url, options, resolve, reject });
this.processQueue();
});
}

async processQueue() {
if (this.activeRequests >= this.maxConcurrent || this.queue.length === 0) {
return;
}

const { url, options, resolve, reject } = this.queue.shift();
this.activeRequests++;

try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), this.timeout);

const response = await fetch(url, {
…options,
signal: controller.signal
});

clearTimeout(timeoutId);

if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}

const data = await response.json();

// 缓存结果
const cacheKey = JSON.stringify({ url, options });
this.cache.set(cacheKey, {
data,
timestamp: Date.now()
});

resolve(data);
} catch (error) {
// 重试逻辑
if (options.retry !== false && this.retryCount > 0) {
options.retry = (options.retry || 0) + 1;
if (options.retry <= this.retryCount) { console.warn(`重试 ${options.retry}/${this.retryCount}: ${url}`); // 重新加入队列 this.queue.unshift({ url, options, resolve, reject }); } else { reject(error); } } else { reject(error); } } finally { this.activeRequests--; this.processQueue(); } } // 批量请求 async batch(requests, batchSize = 3) { const results = []; for (let i = 0; i < requests.length; i += batchSize) { const batch = requests.slice(i, i + batchSize); const batchResults = await Promise.all( batch.map(req => this.request(req.url, req.options))
);
results.push(…batchResults);
}
return results;
}
}

// 使用示例
const manager = new ProductionRequestManager({
maxConcurrent: 4,
timeout: 5000,
retryCount: 2
});

// 并发请求
Promise.all([
manager.request(‘/api/user’),
manager.request(‘/api/posts’),
manager.request(‘/api/comments’)
]).then(results => {
console.log(‘所有数据:’, results);
});
性能优化检查清单
[ ] 是否使用了HTTP/2?
[ ] 是否合并了可以合并的请求?
[ ] 是否实现了适当的缓存策略?
[ ] 是否处理了所有可能的错误情况?
[ ] 是否实现了请求取消机制?
[ ] 是否监控了请求性能?
[ ] 是否考虑了浏览器并发限制?
[ ] 是否实现了优先级管理?
[ ] 是否进行了慢网络测试?
[ ] 是否清理了未完成的请求?
通过遵循这些最佳实践和策略,你可以构建高效、可靠的AJAX并发请求系统,为用户提供流畅的体验。记住,优化是一个持续的过程,需要根据实际应用场景和用户反馈不断调整。