Returning value from asynchronous JavaScript method?

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.

Leave a Comment