【发布时间】:2021-06-10 10:32:19
【问题描述】:
虽然不可能在 try 块中访问其范围之外的变量,但有没有其他方法可以设置它以便可以全局访问?我用的是node.js。
var edata = 0;
if (file !== null)
try {
new ExifImage({ image: myfile }, function myexif(error, exifData) {
if (error) console.log('Error: ' + error.message);
else {
edata = exifData;
// console.log(edata); data is printed here as wanted.
}
});
} catch (error) {
console.log('Error: ' + error.message);
}
console.log(edata); //need to access data here (outside of the scope)
【问题讨论】:
-
该变量在您访问它的范围内可用。这不是范围,而是时间问题。您正在异步操作期间设置变量。使用 Promise 和 async..await。否则,您必须将 console.log 移动到回调中。使用 try..catch 也是错误的,它不会处理来自回调的错误
标签: javascript node.js try-catch exif