-1

I'm pretty sure this is simple, but haven't been able to figure it out.

Have tried using async/await without success.

I have the below function, and I need the const file = removeFirstNRowsFromCsv(listOfFiles[i], 6); line to wait for const file = removeFirstNRowsFromCsv(listOfFiles[i], 6); to resolve to a value (right now is returning undefined and the removeFirstNRowsFromCsv() doesn't resolve until function already errors out).

Any help would be appreciated!

const handleUpload = (listOfFiles) => {
    for (let i = 0; i < listOfFiles.length; i++) { 
        const file = removeFirstNRowsFromCsv(listOfFiles[i], 6);
        dfd.readCSV(file,{skipEmptyLines: true}).then(df => handleQa(df,file, i));
    }
}


// EDITED TO INCLUDE BELOW 
const removeFirstNRowsFromCsv = (csvFileRef, n) => {
    const reader = new FileReader();
    reader.readAsText(csvFileRef);
    reader.onload = function() {
        const csvData = reader.result;
        const csvRows = csvData.split(/\r?\n|\r/);
        const csvRowsNew = csvRows.slice(n);
        const csvRowsNewString = csvRowsNew.join('');
        const blob = new Blob([csvRowsNewString], { type: 'text/csv' });
        const newFile = new File([blob], csvFileRef.name, { type: 'text/csv' });
        return newFile;
    }
}
jmelm93
  • 145
  • 1
  • 10

1 Answers1

0

Async/Await is most likely the way to go. However, removeFirstNRowsFromCSV would need to return a promise for this to work. All async functions return promises, so if this is a function that you wrote, you can make that function async, and then await it in handleUpload. If it doesn't return a promise, you might be able to wrap it in one. For example, if it uses a callback (a lot of older libraries call callback functions after an asynchronous task is completed), you can wrap it in a promise like this:

//assuming removeFirstNRowsFromCsv takes a callback function as the third parameter

const removeNRowsPromise = (a, b) => (
    new Promise((resolve, reject) => removeFirstNRowsFromCsv(a, b, (result) => resolve(result)));
)
jycksyn
  • 31
  • 2
  • _"assuming removeFirstNRowsFromCsv takes a callback"_... it does not (OP updated their question) – Phil Oct 17 '22 at 03:58