I'm new to JS. My main language is Java. So I totally confused with the following code. Idea is to get bunch of files, to parse them, to get a unique string, to make an object, and to push it to result array which is a global variable. Then I need to stringify it and to do some another stuff.
dropArea.addEventListener('drop', handleDrop, false);
var resultArray = {payers: []};
function handleDrop(event) {
let files = event.dataTransfer.files;
processFiles(files, processPayersArray);
}
function processFiles(files, callback) {
([...files]).forEach(file => processSingleFile(file));
callback();
}
function processSingleFile(file) {
let reader = new FileReader();
reader.onload = (function(reader) {
return function() {
reader.result
.split('\n')
.filter(s => s.includes('Плательщик='))
.map(s => s.split('=')[1].trim())
.filter(function(s, pos, arr) {
return arr.indexOf(s) === pos;
})
.forEach(s => resultArray.payers.push(new PayerObj(s)));
}
})(reader);
return reader.readAsText(file, WIN1251);
}
function processPayersArray(array) {
console.log("Array:");
console.log(array);
let json = JSON.stringify(array);
console.log("Json: ");
console.log(json );
}
Console output is totally confuses me:
Array:
{payers: Array(0)}payers: (4) [PayerObj, PayerObj, PayerObj, PayerObj]
Json:
{"payers":[]}
What went wrong? Function processPayersArray is a callback of function processFiles and it have to start after ([...files]).forEach(file => processSingleFile(file)) operation.