2

I'm using exif-js to extract EXIF information from camera/photo gallery images in a Ionic 3 app. I used to catch the onload event and retrieve the EXIF info in a callback and now I want to change the behaviour by using promises but I can't make it work because the function retrieving the EXIF info uses this and I don't understand how to make that accessible to the Promise context.

Here is my old code:

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

The offending line is const allMetaData = exif.getAllTags(this); where this contains a copy of the image enriched with EXIF data.

This is how I converted the function to be async:

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

I've tried several things, including passing resolve to getData with different arguments (this, photo...) without success.

How do I carry getDatacontext over to the promise so thatgetImageEXIFAsync` returns the EXIF data?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Alain1405
  • 2,259
  • 2
  • 21
  • 40
  • in the function as callback this referes to what ? maybe you can decalare a baribale something like let _this = `objectYouWant`, and then pass _this to getAllTags method – Ganesh Karewad Nov 23 '18 at 12:22

1 Answers1

0

What you are looking for is call, apply and bind.

You can find some explanation here

What you want to do is:

exif.getData([YOUR CODE HERE]).call(exif)