【发布时间】: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
}
})
})
}
我尝试了几件事,包括使用不同的参数(this、photo...)将 resolve 传递给 getData,但均未成功。
如何携带getDatacontext over to the promise so thatgetImageEXIFAsync`返回EXIF数据?
【问题讨论】:
-
在回调函数中指的是什么?也许你可以 decalare 一个 baribale 类似 let _this =
objectYouWant,然后将 _this 传递给 getAllTags 方法
标签: javascript asynchronous promise dom-events exif-js