I am trying to figure out what exactly I am missing with these asynch calls. I have a Page class which instantiates a weather object which makes an API call but the program continues to run before the object loads.
When I create a new page instance, Promise {<pending>}
prints to the console then Uncaught TypeError: Cannot read property 'hourly' of undefined
then the fetched weather data prints to the console. It is failing when I try to make the new Rain object because the Weather object instantiation hasn't resolved. Here is the code that is being run:
Page class:
class Page{
constructor(){
this.time = new Time();
this.weather = new Weather('/weather');
console.log(this.weather.data)
this.rain = new Rain(this.weather.data.end.hourly.data);
}
Weather class:
class Weather{
constructor(route){
this.route = route;
this.data = this.get();
// this.data = (async () => await this.get());
}
async get(){
const response = await fetch(this.route);
const data = await response.json();
console.log(data);
return data
}
I also tried setting this.data
in Weather to this.data = (async () => await this.get());
. That returns the same error but this time async () => await this.get()
prints to the console instead of Promise {<pending>}
I feel like I am missing the point where I need to use await.
I have also tried making the constructor call in Page an async init function where this.weather = await new Weather('/weather')
but it still returns Uncaught (in promise) TypeError: Cannot read property 'hourly' of undefined
class Page{
constructor(){
this.init();
}
async init(){
this.time = new Time();
this.weather = await new Weather('/weather');
console.log(this.weather.data)
this.rain = new Rain(this.weather.data.end.hourly.data);
}
Where I am going wrong? In an earlier version of the code, where I did everything from the weather class, it actually worked fine.
class Weather{
constructor(route){
this.route = route;
this.data = null;
this.hour_forecast = {};
this.rain = {
total_prob: null,
max_prob: null,
max_prob_time: null,
max_intensity: null,
max_intensity_time: null
};
}
async init(){
await this.get();
this.predictRain();
this.render();
}
async get(){
const response = await fetch(this.route);
this.data = await response.json();
this.hourly_forecast = this.data.end.hourly.data.slice(0, 11); //gets next 12 hours
console.log(this.data);
}
I was calling the init() after making the weather instance and the get function was setting rather than returning the value but I have been unable to use that information to figure out what I could do differently in the refactored code.