Trying to get a better grasp on Promises with async/await syntax. .then().catch() feels more straightforward with the added visual cues and structure. Do these two async/await functions make any logical sense for making multiple API calls and acting on the data once they're resolved? The goal is to have a function that takes the url, number of additional pages and returns data from all calls in one output. It works but is slow enough to lead me to believe its pretty inefficient. (I'm sure the nested loops dont help)
async function getData(url, numOfPages) {
try {
const response = await axios.get(url)
const { results, next: nextUrl } = response.data
const nextPages = await getNextPages(nextUrl, numOfPages)
const finalData = results.concat(nextPages)
finalData.forEach(data => console.log(data.name))
}
catch (err) {
console.log(err)
}
}
getData('https://swapi.dev/api/planets/', 3)
async function getNextPages(nextUrl, numOfPages) {
try {
const response = await axios.get(nextUrl)
const data = response.data.results.map(res => res)
let nextPage = response.data.next
for (let i = 1; i < numOfPages; i++) {
let response = await axios.get(nextUrl)
let results = response.data.results
nextPage = response.data.next
for (let i = 0; i < results.length; i++) {
data.push(results[i])
}
}
return data
}
catch (err) {
console.log(err)
}
}