0

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.

kirill.login
  • 899
  • 1
  • 13
  • 28
  • `reader.onload` will happen ***sometime later***. The confusing and unfortunate part is just this: https://stackoverflow.com/a/4060176/476. – deceze Jan 23 '19 at 09:16
  • 1
    You are calling `processSingleFile` a bunch of times and them immediately calling `callback`. Sometime later, the `onload` functions you assign *inside* `processSingleFile` finish. You need to call `callback` *after* all the `onload` functions have run. Dealing with a group of async functions is best handled by `promisifying` them and using `Promise.all`. – Quentin Jan 23 '19 at 09:17
  • Thank you @Quentin. Your comment is very helpful. Later I will make a answer with solution. – kirill.login Jan 23 '19 at 09:36
  • The question has been closed. It can't be answered now. – Quentin Jan 23 '19 at 09:37

0 Answers0