TypeScript API如何用forEach获取所有ID并合并对应关联数据?
解决方案
问题分析
你的代码仅针对数组第一个元素的issuer_id调用接口并合并数据,导致其他对象缺失关联字段。要解决这个问题,需要遍历所有含issuer_id的对象,为每个对象单独调用接口并合并结果,同时注意异步操作的正确处理(直接用forEach无法等待异步请求完成)。
修正代码(并行请求,效率优先)
这种方式会同时发起所有接口请求,适合接口无频率限制的场景:
// 将values转为数组,方便遍历 const premiumValues = Object.values(values); // 用Promise.all等待所有异步操作完成 await Promise.all(premiumValues.map(async (item) => { // 跳过没有issuer_id的对象 if (!item.issuer_id) return; // 为当前对象的issuer_id获取三类关联数据 const Communes = await employerDetail.getSingleProfileType(item.issuer_id, 'Communes'); const category = await employerDetail.getSingleProfileType(item.issuer_id, 'company_type'); const location = await employerDetail.getSingleProfileType(item.issuer_id, 'location'); // 将数据合并到当前对象 Object.assign(item, { Communes, category, location }); })); // 返回处理后的数组 return premiumValues;
修正代码(串行请求,适合接口有频率限制)
如果接口存在调用频率限制,可改用for...of串行执行请求:
const premiumValues = Object.values(values); // 逐个遍历对象,串行执行异步请求 for (const item of premiumValues) { if (!item.issuer_id) continue; const Communes = await employerDetail.getSingleProfileType(item.issuer_id, 'Communes'); const category = await employerDetail.getSingleProfileType(item.issuer_id, 'company_type'); const location = await employerDetail.getSingleProfileType(item.issuer_id, 'location'); Object.assign(item, { Communes, category, location }); } return premiumValues;
关键改动说明
- 遍历所有对象:不再只取第一个元素,而是遍历
values转换后的数组中所有对象 - 异步处理:用
Promise.all + map或for...of确保所有异步请求完成后再返回结果,避免数据未加载完成就返回 - 数据合并:为每个对象单独合并对应的关联数据,确保所有含
issuer_id的对象都拥有Communes、category、location字段
内容的提问来源于stack exchange,提问作者jaga b
相关产品推荐
相关产品推荐

