如何使用双重异步map实现ClientFeature模型的批量更新?
解决异步双重映射导致重复赋值的问题
看起来你遇到的问题是因为嵌套的map遍历把每个featureLocalId和所有clientFeature做了组合,导致每个clientFeature被多次更新,每次都用当前遍历到的featureLocalId作为featureId,最后就出现一个featureLocalId被重复赋给多个clientFeatureId的情况(其实是所有clientFeature都被每个featureLocalId更新了一遍,最终结果会被最后一个featureLocalId覆盖)。
你的核心需求应该是把clientFeatures和featureLocalIds按索引一一配对,用对应位置的clientFeature.id更新id字段,featureLocalId更新featureId字段对吧?那我们不需要嵌套的Promise.all和map,只需要单一层的map来配对两个数组的元素:
修正后的代码
let clientFeatures = await ClientFeature.query("clientId") .eq(client.id) .exec(); let featureLocalIds = agreementFeatures.clientFeatureId; // 先校验两个数组长度是否一致,避免索引越界或数据不匹配 if (clientFeatures.length !== featureLocalIds.length) { throw new Error("clientFeatures与featureLocalIds的元素数量不匹配,请检查数据"); } // 按索引配对两个数组的元素,执行异步更新 const updatedClientFeatures = await Promise.all( clientFeatures.map(async (clientFeature, index) => { // 获取当前clientFeature对应的featureId const targetFeatureId = featureLocalIds[index]; // 执行更新操作并返回结果 return ClientFeature.update({ id: clientFeature.id, clientId: client.id, featureId: targetFeatureId, enabled: true }); }) );
为什么原来的代码会出问题?
你原来的逻辑是:
- 遍历每一个
featureLocalIds的item - 对于每个item,又遍历所有
clientFeatures,把这个item作为featureId更新所有clientFeature
这就导致每个clientFeature会被更新N次(N是featureLocalIds的长度),每次都用不同的featureId,最终所有clientFeature的featureId都会被最后一个item覆盖,完全不符合你“一一对应更新”的需求。
补充说明
如果你的需求不是按索引一一配对,而是有其他的关联规则(比如根据某个字段匹配clientFeature和featureLocalId),可以再补充说明具体的匹配逻辑,我们再调整代码~
内容的提问来源于stack exchange,提问作者Bikal Nepal
相关产品推荐
相关产品推荐

