如何在承诺中包装异步函数?

How to wrap an asynchronous function in a promise?

我想在一个承诺中包装一个异步函数,以便它可以 运行 同步。我需要这样做,因为我需要在继续执行我的程序之前检索依赖于异步函数的结果。

这是我的相关代码:

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;
    }
}

运行异步的部分是行var _texture = PIXI.Texture.fromImage(this.imagePath);

加载纹理时,我可以获得纹理的高度。在继续执行我的程序之前,我需要纹理的高度。我怎样才能用一个承诺来包装它,以便它 运行 同步?

我已经查看了这里的其他一些问题,最相关的有一堆被否决和过时的答案,所以我回避了。

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);
     });
}

你只需要一个简单的回调。

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);

}