Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return file content using asynchronous callback response?

I have this code

 function gotFile(file){
    readAsText(file);
}

function readAsText(file) {
    var reader = new FileReader();
    reader.onloadend = function() {  
      var string = evt.target.result;       
    };
      alert(string) // returns null 
    reader.readAsText(file);
}

Apparently I'm trying to get result from asynchronous callback in synchronous function and that's not possible.

So I've changed my code like this :

function gotFile(file){
    readAsText(file,function(str){
        return str;
        });
}

function readAsText(file,callback) {
    var reader = new FileReader();
    reader.onloadend = function() {
     callback(reader.result);
    };
    reader.readAsText(file);
    alert(callback);
}

returns me the string

function(str){
        return str;
}

How can I achieve this ?

Thank you

like image 525
AshBringer Avatar asked Sep 24 '26 15:09

AshBringer


1 Answers

In your updated version you are still trying to use an asynchronous operation as if it were synchronous.

In the callback function, returning the str value is pointless. You need to do something with the str value instead, right there inside callback (or in another function that you call from callback).

For example:

function gotFile(file){
    readAsText(file,function(str){
        alert(str);
    });
}

function readAsText(file,callback) {
    var reader = new FileReader();
    reader.onloadend = function() {
     callback(reader.result);
    };
    reader.readAsText(file);
}

Note the difference: Instead of returning str from callback, we do something with str (call the alert function) right there.

like image 167
Michael Geary Avatar answered Sep 28 '26 06:09

Michael Geary