Tengo una estructura de clases similar y no me funciona, ya probé varias cosas y no puedo solucionar el problema. Como puede ver, los constructores se ejecutan correctamente y también el método ejecutado en el último constructor. Sin embargo, cuando creo contenido HTML, no lo pinta. ¿Por qué y cómo podrías resolver esto?
class AutoComplete{ constructor(){ console.log("constructor autocomplete") this.table = new Table(); } } class Table{ constructor(){ console.log("constructor table") this.arr = [] fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then((data) => { data.map(d => this.arr.push(d)) }); this.fill(); } fill = () => { console.log("fill"); const content = document.querySelector("#content"); // doesn't work this.arr.forEach( ct => { const div = document.createElement("div"); div.innerText = ct.body; content.appendChild(div); //content.innerHTML += div; }); } } let autoc = new AutoComplete(); <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title></title> </head> <body> <div id="content"></div> </body> </html>Esto sucede porque necesita llamar a this.fill() dentro de la función de devolución de llamada .then() . De lo contrario. this.fill se llama antes de recuperar los datos de la API.
Manifestación:
class AutoComplete{ constructor(){ console.log("constructor autocomplete") this.table = new Table(); } } class Table{ constructor(){ console.log("constructor table") this.arr = [] fetch('https://jsonplaceholder.typicode.com/posts') .then((response) => response.json()) .then((data) => { data.map(d => this.arr.push(d)); this.fill(); }) // this.fill() } fill = () => { console.log("fill"); const content = document.querySelector("#content"); // doesn't work this.arr.forEach(ct => { const div = document.createElement("div"); div.innerText = ct.body; content.appendChild(div); //content.innerHTML += div; }); } } let autoc = new AutoComplete(); <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title></title> </head> <body> <div id="content"></div> </body> </html>