简体   繁体   中英

Convert event callback using `this` to promise carrying context

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 getData context over to the promise so that getImageEXIFAsync` returns the EXIF data?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM