原因是这样的。在vue文件中
当时想着很多页面公用一个方法,并且实行多元化使用。
在抽取方法的同时,在最后返回到页面上时,出现了console.log有值,但是页面上却没有的现象,所以判断出是同步异步的问题
API数据
import fetch from '@/utils/fetch'
// 获取Section
export function getSection(id,lcid) {
return fetch({
url: '/section/' + id + '?lcid='+ lcid,
method: 'get'
})
}
// 获取Section列表 (Section章节)
export function getSectionProductList(id,lcid) {
return fetch({
url: '/section/getProductList/' + id + '?lcid='+ lcid,
method: 'get'
})
}
JS方法
import {getSection, getSectionProductList} from '@/api/section'
// 获取section产品list
export async function sectionList(sectionId, lcid) {
// export function sectionList(sectionId, lcid) {
let sectionList = {
id: sectionId,
title: '',
subSectionList: []
}
// method one
// return new Promise(resolve1 => {
// getSection(sectionId, lcid).then(response => {
// sectionList.title = response.data.result.title
// let subSectionList = response.data.result.subSectionList
// if (subSectionList == null || subSectionList.length === 0) {
// return
// }
// // 找子目录
// let tempData = subSectionList.map(list => {
// let obj = {}
// obj.id = list.id
// obj.title = list.title
// return new Promise(resolve => {
// getSectionProductList(list.id, lcid).then(response2 => {
// resolve(response2)
// obj.subSectionValue = response2.data.result
// sectionList.subSectionList.push(obj)
// })
// })
// })
// Promise.all(tempData).then(response => {
// resolve1(sectionList)
// }).catch(_ => {console.log('error')})
// })
// })
// method two
let tempData = await getSection(sectionId, lcid)
sectionList.title = tempData.data.result.title
let subSectionList = tempData.data.result.subSectionList
if (subSectionList == null || subSectionList.length === 0) {
return
}
for (let i = 0; i < subSectionList.length; i++) {
let obj = {}
obj.id = subSectionList[i].id
obj.title = subSectionList[i].title
let tempList = await getSectionProductList(subSectionList[i].id, lcid)
obj.subSectionValue = tempList.data.result
sectionList.subSectionList.push(obj)
}
return sectionList
}
之后写出了2个方法,一个为Promise 一个为await
但是第一种出来以后的数据可能是随机的,需要自己再去排序
下面为postman请求到的数据
getSection