Search code examples
angularangular2-servicestypescript2.0angular5

Delay service call until after loops


I have a function in my component which is to process files into an array and then upload the array to data service by calling one of its functions.

I am parsing uploaded CSV files into an array of JSON data. In the processFiles function, I'm looping through the array to push data into processedData array. Afterwards, I called the this.passData.pushPassedData function from the data service to push the processed data.

The problem is this.passData.pushPassedData function is being executed before the for-loops finished processing the files, and pushing to data service only an empty array.

files = []; // array to store uploaded files
processedData = []; // array to store processed JSON data

processFiles() {
    for (let file of this.files) {
        this.papaService.parse(file, {
            header: true,
            dynamicTyping: true,
            complete: (results) => {
                console.log("Detected: ", results.data);

                for (let entry of results.data) {
                    if (entry.Interface !== "") {
                        let _entry: RuleFormat;

                        _entry = {
                            abc: "xyz",
                            def: "123",
                        }
                        this.processedData.push(_entry);
                        console.log("Pushed: " + JSON.stringify(_entry));
                    }
                }
            }
        })
    }
    console.log("Pushed: " + JSON.stringify(this.processedData));
    this.passData.pushPassedData(this.processedData);
}

From the console, I can see that the data is pushed into the array only after the data service function is called.

Is there any way to make the function call wait for the for-loops?


Solution

  • You could add a counter in processFiles and increment it in the complete callback. You would call this.passData.pushPassedData when all the files have been processed:

    files = []; // array to store uploaded files
    
    processFiles() {
    
        let processedFileCount = 0;
    
        for (let file of this.files) {
            this.papaService.parse(file, {
                ...
    
                complete: (results) => {
                    processedFileCount += 1;
    
                    for (let entry of results.data) {
                        ...
                    }
    
                    if (processedFileCount >= files.length) {
                        // All files have been processed
                        this.passData.pushPassedData(this.processedData);
                    }
                }
            });
        }
    }