async getMaterialInfo() {
  const { proCode, planNum, orderDid } = this.order;
  const params = {
    materialCode: proCode
  };
  const res = await this.$http.get('wareHouse/getMdMaterialBom', { params });
  if (res.result) {
    if (res.values.length === 0) return;
    const material = res.values;
    await Promise.all(material.map(async (e, index) => {
      await this.getMdMaterialBom(e.childMaterialCode, 1, [proCode]);
    }));
    this.$emit('closeLoading');
  }
},
async getMdMaterialBom(materialCode, deep, processed) {
  const { proCode, planNum, orderDid } = this.order;
  const params = {
    materialCode
  };
  const res = await this.$http.get('wareHouse/getMdMaterialBom', { params });
  if (res.result) {
    if (res.values.length === 0) return;
    const material = res.values;
    let fictitious = false;
    await Promise.all(material.map(async (e, index) => {
      if (!processed.includes(e.childMaterialCode)) {
        const filter = this.addTableData.filter(f => f.materialCode === e.materialCode);
        if (filter.length === 0) {
          const obj = {
            materialCode: e.childMaterialCode,
            materialName: e.childMaterialName,
            materialSpec: e.childMaterialSpec,
            stockNum: e.num * planNum * deep,
            maxNum: e.num * planNum * deep,
            orderDid
          };
          if (e.fictitious === 1) {
            fictitious = true;
            await this.getMdMaterialBom(e.childMaterialCode, deep + 1, [...processed, materialCode]);
          } else {
            this.addTableData.push(obj);
          }
        }
      }
    }));
    if (!fictitious) {
      return Promise.resolve('success');
    }
  }
}

优化方式:

  1. 将重复的代码抽取出来,放到一个函数中,避免代码重复。
  2. 对函数参数进行优化,将深度和已处理的材料代码作为参数传入,避免多次查询同一个材料。
  3. 对代码逻辑进行简化,避免深度过多、重复查询等问题。

优化后的代码逻辑:

  1. getMaterialInfo 函数负责获取初始物料信息,并调用 getMdMaterialBom 函数递归查询子物料。
  2. getMdMaterialBom 函数接收三个参数:materialCodedeepprocessed,分别代表当前查询的物料代码、查询深度和已处理的物料代码列表。
  3. getMdMaterialBom 函数首先查询该物料的子物料,然后遍历子物料列表,判断该子物料是否已经处理过。如果未处理过,则将其加入到 addTableData 数组中,并将该子物料代码加入到 processed 列表中。
  4. 如果子物料是虚拟物料,则递归调用 getMdMaterialBom 函数查询其子物料。
  5. 递归查询结束后,如果未发现虚拟物料,则返回 success

代码优化后,避免了重复查询,提高了代码效率。

获取物料信息并递归查询子物料的优化方案

原文地址: https://www.cveoy.top/t/topic/lLnp 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录