【问题标题】:How to wrap an asynchronous function in a promise?如何将异步函数包装在 Promise 中?
【发布时间】:2017-05-18 05:24:11
【问题描述】:

我想在 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 包装它以使其同步运行?

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

【问题讨论】:

  • fromImage 返回什么?
  • @Phil, fromImage 返回一个 Texture 对象,它只是 pixi.js 中内置的一个对象。如果您有兴趣,可以在这里阅读:pixijs.download/release/docs/PIXI.Texture.html。最重要的是,在继续执行我的程序之前,我需要返回 Texture 对象。
  • PIXI.Texture.fromImage 已经同步返回Texture 不是吗?你不需要承诺还是我错过了什么?
  • @Hereblur,不,PIXI.Texture.fromImage 异步返回纹理

标签: javascript typescript promise pixi.js


【解决方案1】:
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);
     });
}

【讨论】:

  • 在这种情况下,Image 对象是什么?它不是一个 pixi.js 对象,那么它真的需要吗?
  • @PythonNewb 它是HTMLImageElement,html 内置对象。由于图像是在 Web 中异步加载的,因此您需要将其包裹起来以获取其大小(仅在加载后可用)。而PIXI.Texture.fromImage是同步的,它在内部处理异步加载过程。
  • 我想我明白了。纹理在哪里分配?是否应该在解析函数中完成?喜欢resolve(var _texture = PIXI.Texture.from(image); this.texture = _texture)
  • @PythonNewb ,请参阅编辑后的答案。 resolve 就像callback,而仅用于成功结果,而拒绝错误。所以resolve(var _texture = PIXI.Texture.from(image); this.texture = _texture) 不起作用。
  • 谢谢。 resolve(this.texture) 行是做什么的?
【解决方案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);

}

【讨论】:

  • 这也很好用。我想避免回调,因为它们会很快使代码变得混乱。出于某种原因,将高度分配给我的 OperationElement 类中的类属性,然后尝试检索它会导致 undefined,尽管
猜你喜欢
  • 2018-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-22
  • 1970-01-01
  • 2021-02-15
  • 1970-01-01
  • 2021-09-14
相关资源
最近更新 更多