后端有一个接口:
create post : 用于创建一个帖子。
在前端上想要进行封装一个API,用于一次性创建多个post。
请问一般是如何进行封装,是否是需要使用到三方库?
后端有一个接口:
create post : 用于创建一个帖子。
在前端上想要进行封装一个API,用于一次性创建多个post。
请问一般是如何进行封装,是否是需要使用到三方库?
实现方案:
基础封装(无需三方库)
// 封装批量创建函数
const batchCreatePosts = async (postsArray) => {
try {
// 使用 Promise.all 并行发送请求
const responses = await Promise.all(
postsArray.map(post =>
fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(post),
headers: { 'Content-Type': 'application/json' }
})
)
);
// 处理所有响应
const results = await Promise.all(responses.map(res => res.json()));
return { success: true, results };
} catch (error) {
// 错误处理增强
return {
success: false,
error: error.message,
partialData: results?.filter(Boolean) || []
};
}
};
// 调用示例
batchCreatePosts([post1, post2, post3])
.then(console.log);
高级场景优化(推荐三方库)
# 安装优化工具
npm install axios p-limit
import axios from 'axios';
import pLimit from 'p-limit';
// 创建并发控制器(限制5个并行请求)
const limit = pLimit(5);
const advancedBatchCreate = async (postsArray) => {
const promises = postsArray.map(post =>
limit(() =>
axios.post('/api/posts', post)
.then(res => ({ status: 'fulfilled', value: res.data }))
.catch(err => ({ status: 'rejected', reason: err.response?.data }))
)
);
// 使用 allSettled 获取完整结果
const results = await Promise.allSettled(promises);
// 分类处理结果
const successful = results.filter(r => r.status === 'fulfilled');
const failed = results.filter(r => r.status === 'rejected');
return {
total: postsArray.length,
successCount: successful.length,
failedCount: failed.length,
successful,
failed
};
};
关键设计考量:
p-limit
避免浏览器并行请求限制(Chrome 默认6个)是否需要三方库?
最佳实践建议:
10 回答11.2k 阅读
15 回答8.2k 阅读
5 回答4.9k 阅读✓ 已解决
4 回答3.1k 阅读✓ 已解决
2 回答2.8k 阅读✓ 已解决
3 回答4.9k 阅读✓ 已解决
4 回答4.5k 阅读✓ 已解决