循环请求同一个接口,等接口返回数据之后在进行下次循环,同步调用api接口方式

303 阅读1分钟

应用场景:for循环中调用接口,等for循环结束,在进行下面的代码,

必须使用for循环,不能使用forEach


  async getSubjectListData(id){
             let res = await  getSubjectList({competeId: id || ''})
                if(res) {
                    this.subjectName = res.data[0].name
                    for (let i = 0; i < res.data.length; i++) {
                        let child = await this.getModuleListData(res.data[i].id)
                        res.data[i]['children']  = child
                    }
                    this.columns = res.data
                    this.$emit('selectModule',{
                        subjectId: this.columns[0].id,
                        moduleId: this.columns[0].children[0].id
                    })
                }

            },
            getModuleListData(id){
                return new Promise((resolve, reject) => {
                    getModuleList({subjectId: id}).then(resp => {
                        resolve(resp.data)
                        }).catch((res) => {
                        reject()
                    })

                })

            },