1. Modifying an array while iterating over it can lead to skipped elements or unexpected behavior.
2. The resolve function should be called in all execution paths of the promise.
1. 在迭代数组时对其进行修改可能会导致
跳过元素或出现意外行为, 数据不准.
2. 应在 Promise 的所有执行路径中调用 resolve 函数
// Remove the common sku from WH01 and DC01 return sku
async function removeCommonList(omsWh01StockList, returnStockList){
return new Promise((resolve, reject) => {
try {
if (omsWh01StockList && omsWh01StockList.length > 0){
// Remove the common sku from WH01 and DC01 return sku
/**
* @description: 1. Modifying an array while iterating over it can lead to skipped elements or unexpected behavior.
2. The resolve function should be called in all execution paths of the promise.
* @author: Grant
* @date:
*/
for (let i = 0; i < omsWh01StockList.length; i++) {
let el = omsWh01StockList[i];
returnStockList.forEach(rl => {
if(rl.return_sku === el.sku){
console.log("Inner of DC01 return sku and Wh01 sku : ", el.sku);
omsWh01StockList.splice(i, 1)
}
})
}
resolve(omsWh01StockList)
}
} catch (error) {
console.log(error);
}
})
}
Optimized code:
async function filterOMSWhPriority(omsWhPriorityList, omsWh01StockList){
return new Promise((resolve, reject) => {
try {
let filteredList = [];
console.log('Before Splice arr length : ', omsWhPriorityList.length);
// Remove omsWh01StockList in omsWhPriorityList
if(omsWhPriorityList && omsWh01StockList && omsWh01StockList.length > 0 ){
// Create a Set of return SKUs for faster lookup
// let wh01Skus = omsWh01StockList.map(ol => ol.sku);
let wh01Skus = new Set(omsWh01StockList.map(ol => ol.sku));
// Filter out the common SKUs
filteredList = omsWhPriorityList.filter(el => !wh01Skus.has(el.SKU));
resolve(filteredList);
} else {
resolve(omsWhPriorityList);
}
console.log('After Splice arr length : ', filteredList.length > 0 ? filteredList.length : omsWhPriorityList.length);
} catch (error) {
console.log(error);
}
})
}