0

I have following function to convert local file to base64. When I run it, it writes the result (res) to console. How can I return the content of res from the function, so I can use it in another one?

function convertToBase64() {
    var xhr = new XMLHttpRequest();       
        xhr.open("GET", "1.jpg", true); 
        xhr.responseType = "blob";
        xhr.onload = function (e) {
            var reader = new FileReader();
            reader.onload = function(event) {
               var res = event.target.result;
               console.log(res);
        }
        var file = this.response;
        reader.readAsDataURL(file)
    };
    xhr.send()
}

(I am totally new in JavaScript.)

Krejdom
  • 3
  • 4
  • 1
    Via a callback or a promise – slebetman May 20 '20 at 06:28
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) –  May 20 '20 at 06:29

1 Answers1

1

you can pass callback to your function to execute when file loaded

function convertToBase64(onLoad) {
    var xhr = new XMLHttpRequest();       
        xhr.open("GET", "1.jpg", true); 
        xhr.responseType = "blob";
        xhr.onload = function (e) {
            var reader = new FileReader();
            reader.onload = function(event) {
               var res = event.target.result;
               console.log(res);
               onLoad(res);            // callback
        }
        var file = this.response;
        reader.readAsDataURL(file)
    };
    xhr.send()
}

now you can do this :

convertToBase64(function(res) {
    console.log('response loaded' , res);
});
Ali Faris
  • 17,754
  • 10
  • 45
  • 70