1

The base64 for the image prints to the console, but I cannot figure out how to assign this value into a variable. I have been looking around for a while now and cannot seem to find a simply, concise answer. I am really new to JS.

function toDataURL(url, callback) {
    let xhr = new XMLHttpRequest();
    xhr.onload = function () {
        let reader = new FileReader();
        reader.onloadend = function () {
            callback(reader.result);
        };
        reader.readAsDataURL(xhr.response);
    };
    xhr.open('GET', url);
    xhr.responseType = 'blob';
    xhr.send();
    //return xhr.responseText;
}


toDataURL(lpif_anchor_tag_href, function (dataUrl) {
    console.log(dataUrl);
});

toDataURL(lpif_anchor_tag_href_two, function (dataUrl) {
    console.log(dataUrl);
});
Auuussiiee
  • 11
  • 5
  • How about using global variable `result = reader.result` and later you can access via `window.result` – hoangfin Nov 23 '18 at 19:12

2 Answers2

0

The request you are making is asynchronous. This means while it's executing, your code continues on, so when you try to assign it's return value to a variable, it doesn't exist yet. What it returns is a promise.

So you need to do something like this:

var promise1 = new Promise(function(resolve, reject) {
  resolve('Success!');
});

promise1.then(function(value) {
  console.log(value);
  // expected output: "Success!"
});

Also here is another answer that goes into detail for your type of usecase: https://stackoverflow.com/a/47445455/5471957

SpeedOfRound
  • 1,210
  • 11
  • 26
0

You have 2 options

Use callbacks: this way you can access your result only inside callback function

Use synchronous request: not recommended, this way your main thread(browser page) will freeze until your request is completed

var request = new XMLHttpRequest();
request.open('GET', '/bar/foo.txt', false);  // `false` makes the request synchronous
request.send(null);

if (request.status === 200) {
    console.log(request.responseText);
}
Medet Tleukabiluly
  • 11,662
  • 3
  • 34
  • 69