2015-04-24 18 views
5

mi ha questa funzione:valore di ritorno calcolata da JavaScript FileReader evento onload

function doStuff(range, file) { 
    var fr = new FileReader(); 
    var hash = ''; 
    fr.onload = function (e) { 
     var out = "stuff happens here"; 
     hash = asmCrypto.SHA256.hex(out); 
     return hash; 
    }; 
    fr.readAsArrayBuffer(file); 
    return hash; 
} 

In questo momento, la funzione completa prima che l'evento onload è finito, in modo doStuff restituisce sempre "". Penso che una callback sia ciò di cui ho bisogno, ma sono nuovo di javascript e non riesco a spiegarmi come implementarlo in questo caso.

risposta

8

La lettura di file tramite il Lettore file è un'operazione asincrona. Posiziona la tua logica all'interno della funzione onload del lettore di file.

function doStuff(range, file) { 
    var fr = new FileReader(); 
    fr.onload = function (e) { 
     var out = "stuff happens here"; 
     hash = asmCrypto.SHA256.hex(out); 
     /* Place your logic here */ 
    }; 
    fr.readAsArrayBuffer(file); 
} 

È anche possibile passare una funzione di richiamata che verrà eseguita una volta letto il file.

function doStuff(range, file, callback) { 
    var fr = new FileReader(); 
    fr.onload = function (e) { 
     var out = "stuff happens here"; 
     hash = asmCrypto.SHA256.hex(out); 
     /* Assuming callback is function */ 
     callback(hash); 
    }; 
    fr.readAsArrayBuffer(file); 
} 
+1

Qual è il motivo del voto negativo? –

+1

Nessuna idea. Non sembra esserci nulla di sbagliato in questa risposta. – Phylogenesis

+1

@Philogenesis Anche lo stesso qui. Non so perché ppl faccia una semplice votazione :( –