I have a class with an asynchronous method that defines several properties of my object, what I want to achieve is to obtain these properties but only when they have already been defined by my method, something like the load event of html elements.
I leave an example with setTimeout to show that after 2 seconds the property is defined and can be accessed.
class AsyncClass {
constructor(){
this.img;
this.getImg();
}
// Metodo Asyncrono
getImg(){
new Promise(loadImg => {
let img = new Image();
img.onload = function(){
loadImg(this);
}
img.src = 'https://images7.alphacoders.com/803/803071.jpg';
}).then(img => {
this.img = img;
document.getElementById('image').src = this.img.src;
});
}
}
var a = new AsyncClass();
// Aqui mi objeto aun no esta definido
console.log(a.img);
// Espero 2 segundos para poder mostrar mi objeto
setTimeout(function(){
console.log(a.img);
},2000)
#image {
width: 200px;
height: 100px;
}
<img id="image"></img>
Your function
getImg
is asynchronous, and your calls are synchronous, to fix your problem, you can use callback in the functiongetImg
, that way you don't need to usesetTimeout