-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;
    }
}
4
  • you probably need to use a return statement. Commented Oct 17, 2022 at 3:49
  • Please edit your question to include the code for removeFirstNRowsFromCsv Commented Oct 17, 2022 at 3:53
  • 2
    Also, if you have used async/await without success, please show that code as well, and describe how exactly it failed. Commented Oct 17, 2022 at 3:54
  • Looks like you need to promisify FileReader.onload. Commented Oct 17, 2022 at 3:56

1 Answer 1

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)));
)
Sign up to request clarification or add additional context in comments.

1 Comment

"assuming removeFirstNRowsFromCsv takes a callback"... it does not (OP updated their question)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.