跳出循环可不要再用forEach,map也不好用,不妨直接用for循环

148 阅读1分钟

需求:循环一个数组保持请求顺序请求接口,且当前数组的值为1时,又需要异步请求另一个接口根据返回status值跳出本次循环。

解决思路:使用for循环,首先在循环中判断数组中值为1的,用async和await异步请求返回数据状态跳出循环;同时把符合条件的所有请求接口push到一个数组中去,最后Promise.all。

直接上代码:

data() {
  return {
    dataList: [],
    form: {
        params: [],
        tableType: null,
        taskId: null
      },
    titleList: [9, 1, 2]
  }
}
methods: {
   async getList() {
      this.dataList = [];
      const p = [];
      // 循环调用同一个接口
      for (let i = 0,l = this.titleList.length; i < l; i++) {
        this.form.tableType = this.titleList[i];
        if (this.titleList[i] === 1 || this.titleList[i] === 2) {
          // 根据taskStatus值,跳出循环。
          if (this.titleList[i] === 1) {
            const { code, data } = await this.getInfo();
            if( code !== 0 || data.taskStatus !== 1) {
              break;
            }
          }
        } else if (this.titleList[i] === 9) {
          // 清空值。
          this.form.params = [];
        }
        // 把符合条件的接口push到数组中去
        p.push(querysNationalGrants(this.form));
      }
      Promise.all(p)
        .then((res) => {
          res.map((info) => {
            if (info.code == 0) {
              this.dataList.push(info.data) || [];
              this.dataList.map((j) => {
                this.$set(j, "loading", false);
                return j;
              });
            }
          });
        })
        .finally(() => {
          this.loading = false;
        });
    },
    getInfo(){
       return getInfoById(this.form.taskId);
    }
}

坑点:
1、当时还是来了就跳到forEach坑中去了,forEach不能跳出循环
2、然而呢又使用了some (return true 跳出整个循环)

let list = [1, 2, 3, 4, 5];
list.some((value, index) => {
    if(value === 3){
        return true;  //  当内部return true时跳出整个循环
    }
    console.log(value) // 1 2
});

表面上看好像没什么毛病,但是到上面的判断处就是不起作用,纠结了很久。。。估计是我太肤浅了。

鉴定完毕,欢迎友们一起交流学习!!