Turn XMLhttpRequest into a function fails: asynchronity or other?

后端 未结 2 2092
不知归路
不知归路 2021-01-17 03:46

I try to turn an XMLHttpRequest into a function such

var getImageBase64 = function (url) { // code function
    var xhr = new XMLHttpRequest(url); 
    ...          


        
2条回答
  •  既然无缘
    2021-01-17 04:01

    Asynchronous calls in JavaScript (like xhr) can't return values like regular functions. The common pattern used when writing asynchronous functions is this:

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

    So your example translated looks like this:

    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);
    });
    

提交回复
热议问题