這是一個異步函數。這意味着,如果你這樣做:
p.read = function(file) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
console.log('a');
fileReader.onload = function(e) {
console.log('b');
return e.target.result;
}
}
和:
console.log('hello');
p.read('file');
console.log('c');
你會得到
hello
c
a
b
因爲javacript是異步的。非常好的b/c就像這樣,你的代碼是非阻塞的:在閱讀一個大文件的時候很容易做一些事情。
在你的榜樣,你要做的:
p.read = function(file, callback) {
var fileReader = new FileReader();
fileReader.readAsDataURL(file);
fileReader.onload = function(e) {
callback(e.target.result);
}
}
並運行:
p.read('file', function(content) {
console.log(content);
});
您是否嘗試過'fileReader.result'? – Ian
你*不能從異步回調函數中返回任何東西。另請參見[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi
@Bergi我不喜歡我不知道我怎麼沒有看到「回報」。出於某種原因,我認爲他們正在打印該值,並且遇到了該問題 – Ian