Check out this code snippet:
export default class Application extends EventEmitter {
constructor() {
super();
this.config = config;
this.data = {
planets: [planetData]
};
this.init();
let url;
let count;
let planetData = []
let promises = [];
//Loop through multiple pages
for (let p = 1; p < 7; p++) {
url = `https://swapi.boom.dev/api/planets?page=${p}`;
//Fetch data from API
promises.push(fetch(url).then(res => res.json())
.then(data => {
//Append fetched data to array
for (let i = 0; i < data.results.length; i++) {
planetData = planetData.concat(data.results[i]);
}
}));
}
Promise.all(promises)
.then(() => {
console.log(planetData.length, '=>', planetData);
})
}
I'm struggling with assigning the planetData array to this.data{}. I attempted using this.data{ planets: [planetData]
, but it resulted in an error message "Cannot access 'planetData' before initialization" as anticipated. It's likely that my syntax is incorrect, but I'm very new to JavaScript.