In two of my classes, I use async/await functions to retrieve products from the product class.
export default class Products {
async getProducts() : Promise<[]> {
return await import('../data/products.json');
}
}
export default class App {
render() {
this.products = new Products();
this.products.getProducts().then((productsData) => {
// Do stuff
});
}
}
While this approach works well, I want to make modifications to the data in the products class before accessing it in the App class. I attempted to change `getProducts` to `setProducts`, where I initialize the products in the constructor and access them as follows:
async setProducts() : void {
this.products = await import('../data/products.json');
}
public getProducts(): [] {
return this.products;
}
The issue arises when calling `getProducts` because the fetch process isn't completed yet, resulting in undefined data being received by the App class.
My next attempt involved:
public getProducts(): [] {
let products: [];
return this.products.then(dataSet => {
products = dataSet;
});
return products;
}
This also led to receiving undefined values.
I'm looking for a solution that will allow my class or getter method to wait until the products are imported, ensuring that the getter method consistently returns the imported data instead of undefined.
The issue at hand involves resolving the promise within the class method before returning the value. Essentially, I need the method to first return products and then populate with data afterwards. While using setTimeout is an option, it's not considered a good practice.