我正在使用exif js从Ionic 3应用程序中的相机/照片库图像中提取exif信息。我曾经捕捉onload
事件并在回调中检索EXIF信息,现在我想通过使用Promise来改变行为,但我无法使其工作,因为检索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
}
})
})
}
我尝试过几种方法,包括用不同的参数(this
、photo
…(将resolve
传递给getData
,但都没有成功。
如何携带getDatacontext over to the promise so that
getImageEXIFAsync`返回EXIF数据?
您要查找的是call, apply and bind
。
你可以在这里找到一些解释
你想做的是:
exif.getData([此处为您的代码](.call(exif(