0

Though it is not possible to access a variable inside try block outside its scope, is there any other way to set it up so that it is could be accessible globally? I am using this is 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)
Ansul
  • 410
  • 5
  • 12
  • 1
    The variable is available in the scope you're accessing it. This isn't scope but timing issue. You're setting a variable during asynchronous operation. Use promises and async..await. Otherwise you'll have to move console.log inside the callback. Also the use of try..catch is wrong, it won't handle an error from the callback – Estus Flask Mar 12 '21 at 12:01

1 Answers1

0

You have declared it properly https://jsfiddle.net/3u2gwfhz/

var edata = 0;
try {
  edata = 2;
} catch (error) {
  console.log('Error: ' + error.message);
}
   
try {
  console.log(edata);
} catch (error) {
  console.log('Error: ' + error.message);
}
   

But not sure about your code here, it doesn't look correct:

if (error) console.log('Error: ' + error.message);
else {
edata = exifData;
// console.log(edata);  data is printed here as wanted.
return edata;
}
designtocode
  • 2,215
  • 4
  • 21
  • 35