如何在promise中包装异步函数?

时间:2017-01-04 01:52:15

标签: javascript typescript promise pixi.js

我想在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);

加载纹理后,我可以获得纹理的高度。在继续执行程序之前,我需要纹理的高度。我如何用一个promise包装它以便它同步运行?

我已经看过这里的其他一些问题,最相关的问题有一堆贬低和过时的答案,所以我回避它。

2 个答案:

答案 0 :(得分:4)

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 :(得分:2)

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

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

}