0

I have been looking and looking for a way to get a variable outside of a function. Here is a snippet of my code.

for (var i = 0; i < results.length; i++) {
  var rawname = results[i].name
  var name = encodeURIComponent(results[i].name)
  var isdirectory = results[i].isDirectory
  var filesize = '""'
  //var modified = '10/13/15, 10:38:40 AM'
  var modified = ''
  var extension = name.split('.').pop();
  // raw, urlencoded, isdirectory, size, 
  if (extension == 'mp3' || extension == 'flac') {
    getEntryFile(results[i], function(file) {
      jsmediatags.read(file, {
        onSuccess: function(tag) {
          var image = tag.tags.picture;
          if (image) {
            var base64String = "";
            for (var i = 0; i < image.data.length; i++) {
              base64String += String.fromCharCode(image.data[i]);
            }
            var base64 = "data:" + image.format + ";base64," +
              window.btoa(base64String);
          }
        },
        onError: function(error) {
          console.log(error);
        }
      })
    })
    html.push('  {')
    html.push('    name: "' + rawname + '",')
    html.push('    artist: "' + rawname + '",')
    html.push('    image: "' + base64 + '",')
    html.push('    path: "' + name + '",')
    html.push('  },')
  }
}

I need to get the base64 variable ouside the 2 functions and use it in the html.push() function.

Please DO NOT close this question. I have searched stack exchange for similar questions and they havent ever worked.

One method I tried was declaring a window variable using window.base64a = base64 but it just returned undefined. What can I do to get my variable outside the function?

Phix
  • 9,364
  • 4
  • 35
  • 62
Ethan O'Brien
  • 53
  • 1
  • 10
  • why don't you move the html.push code inside the onsucess function? – Nicolas I Apr 22 '21 at 16:09
  • Your question unfortunately **is** a duplicate. Please study the answers in the duplicate thoroughly, try to apply it to your case and only then, if you have a specific question, please return and ask for that. Your real problem is not *how* to make the result accessible (your approach with a global variable will work), but rather *when* is it safe to access that variable. – connexo Apr 22 '21 at 16:09
  • 1
    i see that the function you're getting trouble with is a callback. Then the problem is about async code and not just about variables – malarres Apr 22 '21 at 16:11

0 Answers0