Returning value from asynchronous JavaScript method?

后端 未结 2 1667
清酒与你
清酒与你 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条回答
  •  猫巷女王i
    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.

提交回复
热议问题