vue中调用后端接口的一个问题

问题遇到的现象和发生背景

如下代码,我在getInfo中对两个接口进行调用,为什么我把 subject.getSubjectList()写在 course.getCourseInfoById(this.courseId)里面, this.subjectOneList 才能赋值。

正确代码

methods: {
//根据courseId查询课程信息
getInfo(){
course.getCourseInfoById(this.courseId)
.then(response => {
this.courseInfo = response.data.courseInfo

                subject.getSubjectList()
                    .then(response => {
                        this.subjectOneList = response.data.data
                        this.subjectOneList.forEach(oneSubject => {
                            if(oneSubject.id === this.courseInfo.subjectParentId){
                                this.subjectTwoList = oneSubject.children
                            }
                        })
                    })
                //初始化讲师信息
                this.getListTeacher()
            })
    },

}

错误代码

methods: {
//根据courseId查询课程信息
getInfo(){
course.getCourseInfoById(this.courseId)
.then(response => {
this.courseInfo = response.data.courseInfo
})
subject.getSubjectList()
.then(response => {
this.subjectOneList = response.data.data
this.subjectOneList.forEach(oneSubject => {
if(oneSubject.id === this.courseInfo.subjectParentId){
this.subjectTwoList = oneSubject.children
}
})
//初始化讲师信息
this.getListTeacher()
})
},
}
我写成这样 this.subjectOneList永远是个空的为什么

检查下两种情况下,subject.getSubjectList()这个函数调用的接口请求是不是都能拿到数据,两次的请求参数是不是一致

给你找了一篇非常好的博客,你可以看看是否有帮助,链接:vue循环请求一个接口

subject.getSubjectList() 这个代码是什么,是不是用到了course.getCourseInfoById 里面的数据,在运行 subject.getSubjectList()时 course.getCourseInfoById 的数据还没有加载完成