How to wrap an asynchronous function in a promise?

2.7k Views Asked by At

I want to wrap an asynchronous function in a promise so that it can run synchronously. I need to do this because I need to retrieve a result that depends on the asynchronous function before continuing with the execution of my program.

Here is my relevant code:

export abstract class OperationElement extends Sprite {

    private imagePath;

    abstract setPosition(mousePosition?, backgroundHeight?, backgroundWidth?) : void;

    loadTexture(){
         var _texture = PIXI.Texture.fromImage(this.imagePath);
         this.texture = _texture;
         console.log(this.height);
    }

    setImagePath(path : string){
         this.imagePath = path;
    }
}

The part that runs async is the line var _texture = PIXI.Texture.fromImage(this.imagePath);

When the texture is loaded, I can get the height of the texture. I need the height of the texture before I can continue execution of my program. How can I wrap this with a promise so that it runs synchronously?

I've taken a look at some other questions around here, the most relevant had a bunch of downvoted and out of date answers so I shy away from that.

2

There are 2 best solutions below

10
On BEST ANSWER
loadTexture():Promise<PIXI.Texture> {  
     return new Promise<PIXI.Texture>((resolve, reject) => {
         var image = new Image();
         image.src = this.imagePath;
         image.onload = () => {
             console.log(image.height);
             this.texture = PIXI.Texture.from(image);
             resolve(this.texture);
         }
         image.onerror = e => reject(e);
     });
}
1
On

You just need a simple callback.

onTextureLoaded(){

    console.log( this.texture.height )
    this.texture.off('update', this.onTextureLoaded, this);

}

loadTexture(){
    var _texture = PIXI.Texture.fromImage(this.imagePath);
    this.texture = _texture;

    this.texture.on('update', this.onTextureLoaded, this);

}