knights
knights

Reputation: 1

How to return string from an onload function in JavaScript

I have this function to convert an image uploaded through an input into base64 string. How do I return it so that when I call this function later on (see below), I am returning the base64 string?

// Convert to Base64
function getBase64(file) {
  var reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = function () {
    let base64String = reader.result.split(',').pop();
    console.log(base64String);
    return base64String;
  };
  reader.onerror = function (error) {
    console.log('Error: ', error);
  };
}

This is where I call the function:

// Post a new tweet
function postTweet() {
    var mediaid = "";
    var file = document.querySelector('input[type=file]').files[0];
    var img = getBase64(file);
    var params = {
        "media_data": img
    };
    cb.__call(
        "media_upload",
        params,
        function (reply, rate, err) {
            mediaid = reply.media_id_string;
            console.log(reply);
            cb.__call(
                "statuses_update", {
                    media_ids: mediaid,
                    status: document.getElementById("tweet").value
                },
                function (reply, rate, err) {
                    console.log(reply);
                }
            );
        }
    );
};

Upvotes: 0

Views: 40

Answers (0)

Related Questions