【问题标题】:Convert event callback using `this` to promise carrying context使用 `this` 将事件回调转换为承诺携带上下文
【发布时间】:2019-04-26 00:57:42
【问题描述】:

我正在使用 exif-js 从 Ionic 3 应用程序中的相机/照片库图像中提取 EXIF 信息。我曾经捕获onload 事件并在回调中检索EXIF 信息,现在我想通过使用promises 来更改行为,但我无法使其工作,因为检索EXIF 信息的函数使用this 而我没有'不明白如何让 Promise 上下文可以访问它。

这是我的旧代码:

public getImageEXIF(imagePath) {
    let imageR = new Image();
    imageR.onload = function () {
      exif.getData(imageR, function () {
        const allMetaData = exif.getAllTags(this);
      });
    };
    imageR.src = imagePath;
  }

违规行是const allMetaData = exif.getAllTags(this);,其中this 包含用EXIF 数据丰富的图像副本。

这就是我将函数转换为异步的方式:

 public waitImageLoad(imagePath): Promise<any> {
    return new Promise((resolve) => {
      let photo = new Image();
      photo.onload = () => resolve(photo)
      photo.src = imagePath;
    });
  }

public getImageEXIFAsync(imagePath) {
    this.waitImageLoad(imagePath).then((photo) => {
      exif.getData(photo, () => {
        // Here `this` points to the class to which `getImageEXIFAsync` belongs to
        const allMetaData = exif.getAllTags(this);
        console.log(lat, long);

        if (lat && long) {
          return { latitude: lat, longitude: long }
        } else {
          return null
        }
      })
    })
  }

我尝试了几件事,包括使用不同的参数(thisphoto...)将 resolve 传递给 getData,但均未成功。

如何携带getDatacontext over to the promise so thatgetImageEXIFAsync`返回EXIF数据?

【问题讨论】:

  • 在回调函数中指的是什么?也许你可以 decalare 一个 baribale 类似 let _this = objectYouWant,然后将 _this 传递给 getAllTags 方法

标签: javascript asynchronous promise dom-events exif-js


【解决方案1】:

你要找的是call, apply and bind

You can find some explanation here

你想做的是:

exif.getData([您的代码]).call(exif)

【讨论】:

    猜你喜欢
    • 2018-05-04
    • 2018-08-08
    • 1970-01-01
    • 2020-06-02
    • 1970-01-01
    • 2014-12-02
    • 2015-08-10
    • 2016-08-30
    • 2017-07-07
    相关资源
    最近更新 更多