Convertir XMLhttpRequest en una función falla: ¿asincronidad u otra?
Intento convertir un XMLHttpRequest en una función como
var getImageBase64 = function (url) { // code function
var xhr = new XMLHttpRequest(url);
... // code to load file
... // code to convert data to base64
return wanted_result; // return result of conversion
}
var newData = getImageBase64('http://fiddle.jshell.net/img/logo.png'); // function call
doSomethingWithData($("#hook"), newData); // reinjecting newData in wanted place.
Tengo éxito al cargar el archivo y convertirlo a base64. Sin embargo, estoy fallando constantementepara obtener el resultado como salida :
var getImageBase64 = function (url) {
// 1. Loading file from url:
var xhr = new XMLHttpRequest(url);
xhr.open('GET', url, true); // url is the url of a PNG image.
xhr.responseType = 'arraybuffer';
xhr.onload = function(e) {
if (this.status == 200) { // 2. When loaded, do:
console.log("1:Response?> " + this.response); // print-check xhr response
var imgBase64 = converterEngine(this.response); // converter
}
}
xhr.send();
return xhr.onload(); // <fails> to get imgBase64 value as the function's result.
}
console.log("4>>> " + getImageBase64('http://fiddle.jshell.net/img/logo.png') ) // THIS SHOULD PRINT THE BASE64 CODE (returned resukt of the function getImageBase64)
VerViolín aquí.
¿Cómo hacer que funcione para que devuelva los nuevos datos como salida?
Solución: mi implementación final esvisible aquí, y enJS: ¿cómo cargar una imagen de mapa de bits y obtener su código base64?.