如何return文件内容使用异步回调响应?

How to return file content using asynchronous callback response?

我有这个代码

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

显然我正在尝试从同步函数中的异步回调中获取结果,但这是不可能的。

所以我更改了我的代码:

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 我的字符串

function(str){
        return str;
}

我怎样才能做到这一点?

谢谢

在您的更新版本中,您仍在尝试将异步操作当作同步操作来使用。

callback函数中,返回str值是没有意义的。您需要 执行 str 的操作,就在 callback 内部(或在您 调用的另一个函数中 来自 callback).

例如:

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

注意区别:我们不是从 callback 返回 str,而是直接用 str 做一些事情(调用 alert 函数)。