如何让SKU遍历循环在GetAllProductInfo出错后继续执行
如何让循环在捕获异步错误后继续处理下一个SKU?
初始代码
const name = ["shoes", "hoodies", "trousers"] //示例:这些是我们的产品名称 const ProductSKU = await GetProductSKUFromApi(name) //针对每个产品(如shoes)返回多个SKU const length = Object.keys(ProductSKU).length //统计SKU的数量 for(let i = 0; i < length; i++){ try { const SKU = ProductSKU[i]["sku"] //逐个获取SKU console.log(SKU) //查看当前循环正在处理的SKU const ProductInfo = await GetAllProductInfo(SKU) //传入SKU获取产品数据 console.log(ProductInfo) //获取产品信息 } catch (error) { console.log(error) } }
问题描述
执行const ProductInfo = await GetAllProductInfo(SKU)时,若该函数报错,整个循环会中断,无法继续处理后续SKU。
解决方案
核心是确保每次循环的异步操作及相关逻辑都被独立的try/catch包裹,同时修正原代码中可能存在的遍历逻辑错误。
优化后的代码(按产品分组的SKU对象场景)
如果GetProductSKUFromApi返回的是按产品名称分组的对象(比如{ shoes: [ {sku: 'xxx'}, ... ], ... }),使用for...of遍历更合理:
const name = ["shoes", "hoodies", "trousers"]; const ProductSKU = await GetProductSKUFromApi(name); // 遍历每个产品对应的SKU列表 for (const productKey of Object.keys(ProductSKU)) { const skuList = ProductSKU[productKey]; for (const skuItem of skuList) { try { const currentSKU = skuItem.sku; console.log(`正在处理SKU: ${currentSKU}`); // 异步请求出错时会被catch捕获,不中断循环 const productInfo = await GetAllProductInfo(currentSKU); console.log(`SKU ${currentSKU} 处理完成:`, productInfo); } catch (error) { // 记录错误但继续循环 console.error(`SKU ${skuItem.sku || '未知'} 处理失败:`, error.message); } } }
简化版(SKU为数组场景)
如果GetProductSKUFromApi直接返回所有SKU的数组,代码可以更简洁:
const name = ["shoes", "hoodies", "trousers"]; const ProductSKU = await GetProductSKUFromApi(name); for (const skuItem of ProductSKU) { try { const currentSKU = skuItem.sku; console.log(`正在处理SKU: ${currentSKU}`); const productInfo = await GetAllProductInfo(currentSKU); console.log(`SKU ${currentSKU} 处理完成:`, productInfo); } catch (error) { console.error(`SKU ${currentSKU || '未知'} 处理失败:`, error.message); } }
关键说明
- 独立的try/catch:每个循环迭代的逻辑都被单独的
try/catch包裹,单个SKU处理出错时,错误会被捕获并记录,循环自动进入下一次迭代。 - 遍历方式修正:用
for...of替代传统索引循环,避免原代码中用数字索引访问对象属性导致的潜在错误(比如ProductSKU[i]返回undefined后访问sku的问题)。 - 清晰的错误日志:明确标记出错的SKU,方便后续排查问题。
内容的提问来源于stack exchange,提问作者AZAZIN LOVE
相关产品推荐
相关产品推荐

