Я могу получать данные из API, и я могу просматривать несколько страниц данных, если есть несколько страниц. Однако, чтобы ускорить его, я хотел бы попытаться получить несколько страниц одновременно.
Но я не могу заставить этот код работать.
async people() {
// https://swapi.co/api/people/
// The API returns 10 items per page
const perPage = 10
let promises = []
// Start with an empty array and add the results from each API call
let allResults = []
// Get first page and total number of pages
// based on total number of results (data.count)
let people = await fetch(`https://swapi.co/api/people`)
let data = await people.json()
const totalPages = Math.ceil(data.count / perPage)
// Add results to array
allResults = allResults.concat(data.results)
// If the total results is greater than the results per page,
// get the rest of the results and add to the aLLResults array
if (data.count > perPage) {
for (let page = 2; page <= totalPages; page++) {
promises.push(
new Promise((resolve, reject) => {
people = fetch(`https://swapi.co/api/people/?page=${page}`).
then(response => {
data = response.json()
},
response => {
allResults = allResults.concat(response.results)
}
)
})
)
}
return Promise.all(promises)
}
return allResults
},