Returning value from asynchronous JavaScript method?

后端 未结 2 1641
清酒与你
清酒与你 2020-11-27 07:29

I have run into a problem where I can\'t seem to get a value from an asynchronous JavaScript method I am running in Jquery. My Jquery looks like this:

$(docu         


        
相关标签:
2条回答
  • 2020-11-27 08:08

    Your best bet is to pass a callback to create_blob and let the callback do whatever needs to be done, something like this:

    create_blob(file, function(blob_string) { alert(blob_string) });
    
    function create_blob(file, callback) {
        var reader = new FileReader();
        reader.onload = function() { callback(reader.result) };
        reader.readAsDataURL(file);
    }
    

    This sort of chicanery is pretty standard with asynchronous calls (AJAX in particular). You could wire up some fragile mess of timers in an attempt for force synchronically but fighting the natural style of an API is a losing battle.

    0 讨论(0)
  • 2020-11-27 08:09

    This is the issue with callbacks. The 'answer' is going to happen later in another moment and not during the evaluation of the method. Little use making a return here.

    Your callback needs to handle the return value making the code looks more complicated :

    reader.onload = function(e) { 
      // handle here the result
      // do something with e.target.result
    };
    
    0 讨论(0)
提交回复
热议问题