基于父分类ID利用Promise获取子分类并批量入库的技术问询
看起来你已经搭建好了获取分类的Promise流程,现在要把这些分类插入数据库对吧?我来帮你梳理下可行的实现方案,顺便优化下现有代码里的冗余部分~
第一步:优化现有分类获取逻辑
你的现有代码里anAsyncFunction其实是多余的(只是简单转发调用),而且原来的functionWithPromise获取了子分类数据却没用到,我们先把这部分逻辑整合优化,同时保留父分类和对应的子分类数据,方便后续插入:
const getData = async () => { // 获取所有一级父分类 const parentRes = await fetch('API/categories?parent=0'); const parentCategories = await parentRes.json(); // 对每个父分类,获取其子分类,返回包含父+子的组合对象 return Promise.all(parentCategories.map(async (parent) => { const childRes = await fetch(`API/categories?parent=${parent.id}`); const childCategories = await childRes.json(); return { parent, children: childCategories }; })); }
第二步:实现分类插入逻辑
接下来我们需要把收集到的父分类和子分类都插入数据库,这里有三种常见方案,你可以根据API的并发限制和业务需求选择:
方案一:全量并行插入(效率最高)
如果你的API允许高并发请求,这种方式会同时发起所有插入请求,速度最快:
const insertAllCategories = async () => { try { const categoryGroups = await getData(); // 把父分类和所有子分类合并成一个数组 const allCategories = []; categoryGroups.forEach(group => { allCategories.push(group.parent); allCategories.push(...group.children); }); // 并行执行所有插入请求 await Promise.all(allCategories.map(category => api.create(category))); console.log('🎉 所有分类插入成功!'); } catch (error) { console.error('❌ 插入分类失败:', error); throw error; // 可根据业务需求做错误降级或重试 } }
方案二:顺序插入(最稳妥)
如果API对并发请求有限制,或者你需要严格按照「父分类→子分类」的顺序插入,可以用for...of循环逐个执行:
const insertAllCategories = async () => { try { const categoryGroups = await getData(); for (const group of categoryGroups) { // 先插入当前父分类 await api.create(group.parent); console.log(`✅ 父分类「${group.parent.name}」插入成功`); // 再逐个插入该父分类下的子分类 for (const child of group.children) { await api.create(child); console.log(`✅ 子分类「${child.name}」插入成功`); } } console.log('🎉 所有分类插入完成!'); } catch (error) { console.error('❌ 插入过程出错:', error); throw error; } }
方案三:分批并行插入(兼顾效率与并发限制)
如果分类数量特别多,既想保证插入效率,又不想触发API限流,可以采用分批并行的方式:
// 通用分批插入工具函数 const batchInsert = async (items, batchSize = 10) => { for (let i = 0; i < items.length; i += batchSize) { const currentBatch = items.slice(i, i + batchSize); await Promise.all(currentBatch.map(item => api.create(item))); console.log(`✅ 完成第 ${Math.floor(i/batchSize)+1} 批插入,共插入 ${currentBatch.length} 条数据`); } } // 主插入函数 const insertAllCategories = async () => { try { const categoryGroups = await getData(); const allCategories = []; categoryGroups.forEach(group => { allCategories.push(group.parent); allCategories.push(...group.children); }); // 每批插入10条,可根据API限制调整批次大小 await batchInsert(allCategories, 10); console.log('🎉 所有分类插入成功!'); } catch (error) { console.error('❌ 插入分类失败:', error); throw error; } }
最后:启动插入流程
当你需要执行分类插入时,直接调用insertAllCategories()即可:
// 触发插入操作 insertAllCategories();
内容的提问来源于stack exchange,提问作者Yasir
相关产品推荐
相关产品推荐

