2014-03-06 155 views
0

這是我的文件閱讀器:文件讀取器 - 返回文件?

p.read = function(file) { 
    var fileReader = new FileReader(); 
    fileReader.readAsDataURL(file); 
    fileReader.onload = function(e) { 

     return e.target.result; 
    } 
} 

但沒有什麼是恢復?任何想法爲什麼?

+0

您是否嘗試過'fileReader.result'? – Ian

+1

你*不能從異步回調函數中返回任何東西。另請參見[如何從AJAX調用返回響應?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – Bergi

+0

@Bergi我不喜歡我不知道我怎麼沒有看到「回報」。出於某種原因,我認爲他們正在打印該值,並且遇到了該問題 – Ian

回答

0

恐怕你不能從一個回調函數

嘗試它返回到它的另一個功能

分開,我希望我幫助

0

這是一個異步函數。這意味着,如果你這樣做:

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