将XMLhttpRequest转换为函数失败:异步或其他

Turn XMLhttpRequest into a function fails: asynchronity or other?

本文关键字:异步 其他 失败 函数 XMLhttpRequest 转换      更新时间:2023-09-26

我尝试将XMLHttpRequest转换为如下函数

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.

我成功加载文件,并转换为base64。然而,我总是无法将作为输出:

获得结果。
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)

参见此处提琴

如何使它工作,使它返回新的数据作为输出?


解决方案:我的最终实现在这里可见,在JS上:如何加载位图图像并获得其base64代码?

JavaScript中的异步调用(如xhr)不能像常规函数那样返回值。编写异步函数时使用的常见模式如下:

function asyncFunc(param1, param2, callback) {
  var result = doSomething();
  callback(result);
}
asyncFunc('foo', 'bar', function(result) {
  // result is what you want
});

所以你的例子翻译成这样:

var getImageBase64 = function (url, callback) {
    var xhr = new XMLHttpRequest(url); 
    ... // code to load file 
    ... // code to convert data to base64
    callback(wanted_result);
}
getImageBase64('http://fiddle.jshell.net/img/logo.png', function(newData) {
  doSomethingWithData($("#hook"), newData);
});

当你使用xhr。onload实际上定义了JS在加载时调用的函数,因此是xhr的值。Onload是函数本身,而不是函数的输出。返回xhr.onload()将调用该函数并返回输出,但是您的onload函数没有返回语句,因此没有输出。另外,您正在呼叫xhr。在设置对象时同步Onload,因此它不会有任何数据需要处理。

我建议你添加一个回调参数到你的函数,像这样,这将执行当数据加载。

function getImageBase64( url, callback) {
    // 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.callback = callback;
    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
            this.callback(imgBase64);//execute callback function with data
        }
    }
    xhr.send();
}

那么你可以这样使用

var myCallBack = function(data){
    alert(data);
};
getImageBase64('http://fiddle.jshell.net/img/logo.png', myCallBack);