This isn't a technical problem that needs a solution but more that I'm wanting a better technical understanding of JavaScript and recursive functions.
I wrote a recursive function to call an API to get all the records until there were no records left to get.
Below is its basic working form. That returns the expected number of records in the array.
async function getRecords(page, recordsArray) {
const records = await <axios api call>
const moreRecords = records.more_records
if(!moreRecords) {
return recordsArray.concat(records.data)
} else {
return await getRecords(page + 1, recordsArray.concat(records.data))
}
}
However, when I originally wrote this function I did it like the one below which didn't return the expected number of records and I don't really understand why. I expected it would.
async function getRecords(page, recordsArray) {
const records = await <axios api call>
const moreRecords = records.more_records
if(!moreRecords) {
recordsArray.concat(records.data)
return recordsArray
} else {
return await getRecords(page + 1, recordsArray.concat(records.data))
}
}
QUESTION
Why did the second not return the expected number of records but the first did?