Simulate load event in a javascript class

1

I have a class with an ascynchronous method that defines several properties of my object, what I want to achieve is to obtain these properties but only when they were already defined by my method, something like the load event of the html elements.

I leave an example with setTimeout to show that after 2 seconds the property is defined and can now 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>
    
asked by Edwin V 19.02.2017 в 02:13
source

1 answer

1

Your function getImg is asynchronous, and your calls are synchronous, to solve your problem, you can use callback in the function getImg , that way it is not necessary to use setTimeout

class AsyncClass {
  constructor(){
    this.img;
  }
  // Metodo Asyncrono
  getImg(done){
    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;
      return done(null,this.img);
    });
  }
  
}

var a = new AsyncClass();
a.getImg(function(err,img){
console.log(img);
})
#image {
  width: 200px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img id="image"></img>
    
answered by 19.02.2017 / 02:44
source