Javascript 使用“this”将事件回调转换为上下文
我正在使用Ionic 3应用程序从相机/照片库图像中提取EXIF信息。我过去常常捕获Javascript 使用“this”将事件回调转换为上下文,javascript,asynchronous,promise,dom-events,exif-js,Javascript,Asynchronous,Promise,Dom Events,Exif Js,我正在使用Ionic 3应用程序从相机/照片库图像中提取EXIF信息。我过去常常捕获onload事件并在回调中检索EXIF信息,现在我想通过使用承诺来更改行为,但我无法使其工作,因为检索EXIF信息的函数使用this,我不明白如何使承诺上下文能够访问它 这是我的旧代码: public getImageEXIF(imagePath) { let imageR = new Image(); imageR.onload = function () { exif.getDat
onload
事件并在回调中检索EXIF信息,现在我想通过使用承诺来更改行为,但我无法使其工作,因为检索EXIF信息的函数使用this
,我不明白如何使承诺上下文能够访问它
这是我的旧代码:
public getImageEXIF(imagePath) {
let imageR = new Image();
imageR.onload = function () {
exif.getData(imageR, function () {
const allMetaData = exif.getAllTags(this);
});
};
imageR.src = imagePath;
}
有问题的行是constAllMetadata=exif.getAllTags(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
}
})
})
}
public waitImageLoad(imagePath):将Promise上下文转移到Promise,以便
getImageEXIFAsync`返回EXIF数据?您要查找的是调用、应用和绑定
您要做的是:
exif.getData([此处的代码]).call(exif)在函数中作为回调引用什么?也许你可以像让_this=objectYouWant
那样,将它传递给getAllTags方法