function load_files (event)
var file;
var reader;
var lines = [];
for (file of event.target.files)
reader = new FileReader();
reader.onload = function (event)
let l = this.result.split (/\r?\n/); // lines to add
for (let i = 0; i < l.length; i++)
lines.push(l[i]);
reader.readAsText (file);
// how to wait for all onload functions here?
replace_log(lines.sort());
}
function load_files (event) {
var file;
var reader;
var lines = [];
let count = 0;
for (file of event.target.files) {
reader = new FileReader();
// this event is triggered only in case of success
reader.onload = function (event) {
let l = this.result.split (/\r?\n/); // lines to add
for (let i = 0; i < l.length; i++)
lines.push(l[i]);
// this event is triggered both in case of success or failure when the op. is completed
reader.onloadend = function(event) {
if(++count === event.target.files.length)
replace_log(lines.sort());
reader.readAsText (file);
}
或者,您也可以使用Promises
代码语言:
javascript
复制
function read_file(file) {
return new Promise((resolve, reject) => {
var fr = new FileReader();
fr.onload = () => {
resolve(fr.result);
fr.readAsText(file);
function load_files(event) {
var file;
var reader;
var lines = [];
let count = 0;
let promises = []; // collect all promises
for (file of event.target.files) {
promises.push(read_file(file));
Promise.all(promises) // wait for the resolutions
.then(results => {
for (result of results) {
let l = result.split(/\r?\n/); // lines to add