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