2
我有這樣的代碼如何使用異步回調響應來返回文件內容?
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);
}
返回我的字符串
function(str){
return str;
}
我怎樣才能做到這一點?
謝謝
我想把這個字符串值放入一個全局變量中並在其他函數中使用它。做一個警報對我沒有幫助 – AshBringer
你的其他函數將如何知道字符串值已準備好?它不會。你需要從你的回調中調用其他函數。 –
真的嗎?我不能在這個函數中等待它,並在另一個之後使用它? – AshBringer