Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from asynchronous JavaScript method?

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:

$(document).ready( function() {
$('#splash_image_upload').change( function() {
    var file = this.files[0];
    var blob_string = create_blob(file);
    alert(blob_string);
 });

I am able to access the value that comes from the 'onload' event but I cannot seem to return the actual value. I have tried this:`

function create_blob(file) {
    var reader = new FileReader();
    reader.onload = (function() { return function(e) { return e.target.result; }; })();
    reader.readAsDataURL(file);
}

Every time I execute this function the value of the 'blob_str' variable is 'undefined' presumably because the assignment is done before the function is finished. I am not really sure how to go about this. Is there a way I can return this value from this function??

like image 372
Kevin Avatar asked Jun 02 '11 06:06

Kevin


1 Answers

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.

like image 101
mu is too short Avatar answered Nov 13 '22 20:11

mu is too short