我想編譯一個數據列表,我從多個API調用中獲得的數據,但有問題與構建陣列和陷入無限遞歸。追加數組與遞歸承諾,Javascript
函數調用遞歸函數:
jsonToCsv() {
this.exportCSV().then(data => {
console.log('From jsonToCSV', data)
})
}
遞歸函數
exportCSV (uidList = this.checkboxList.slice(), offset = 0) {
// Get query, build request
let request = {
id: 'export',
query: this.currentQuery.query,
sort: this.currentQuery.sort,
limit: 100, // how much data is returned
offset: offset // pagination value
}
return new Promise((resolve, reject) => {
// using Vuex to fetch data, returns an array of objects.
this.$store.dispatch('show/fetchQuery', request).then(data => {
let headerList = this.shownHeaders // an array of column id's & thier 'nice names'
let output = []
let row, uid, header
// match the id's to the Data from the API call
for (uid = 0; uid < uidList.length; uid++) {
for (row = 0; row < data.length; row++) {
if (data[row].uid === uidList[uid]) {
let rowData = {}
uidList.splice(uid, 1) // found this id so remove from list
// take data from query call that we want, make objects, push them to array
for (header = 0; header < headerList.length; header++) {
let niceName = headerList[header].niceName
let id = headerList[header].id
rowData[niceName] = data[row][id]
}
output.push(rowData)
}
}
}
// Basecase
if (uidList.length === 0) {
resolve(output)
return
}
offset += 100 // get next 100 results from query
// run next recursive call
this.exportCSV(uidList, offset).then(newData => {
output.push(newData)
resolve(newData)
})
})
})
我相信我正確處理basecase,但是,如果查詢被稱爲多比一次,意味着2級遞歸,只有最新的遞歸調用返回值被打印出來。數組輸出被覆蓋..如果不滿足basecase,我該如何處理解析數據?