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

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

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

直接上代码:

 1 data() {
 2   return {
 3     dataList: [],
 4     form: {
 5         params: [],
 6         tableType: null,
 7         taskId: null
 8       },
 9     titleList: [9, 1, 2]
10   }  
11 }
12 methods: {
13    async getList() {
14       this.dataList = [];
15       const p = [];
16       // 循环调用同一个接口
17       for (let i = 0,l = this.titleList.length; i < l; i++) {
18         this.form.tableType = this.titleList[i];
19         if (this.titleList[i] === 1 || this.titleList[i] === 2) {
20           // 根据taskStatus值,跳出循环。
21           if (this.titleList[i] === 1) {
22             const { code, data } = await this.getInfo();
23             if( code !== 0 || data.taskStatus !== 1) {
24               break;
25             }
26           }
27         } else if (this.titleList[i] === 9) {
28           // 清空值。
29           this.form.params = [];
30         }
31         // 把符合条件的接口push到数组中去
32         p.push(querysNationalGrants(this.form));
33       }
34       Promise.all(p)
35         .then((res) => {
36           res.map((info) => {
37             if (info.code == 0) {
38               this.dataList.push(info.data) || [];
39               this.dataList.map((j) => {
40                 this.$set(j, "loading", false);
41                 return j;
42               });
43             }
44           });
45         })
46         .finally(() => {
47           this.loading = false;
48         });
49     },
50     getInfo(){
51        return getInfoById(this.form.taskId);
52     }
53 }

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

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

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

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

posted @ 2023-07-11 11:39  红石榴21  阅读(13)  评论(0编辑  收藏  举报