How to use Promises with PapaParse?

PapaParse has an asynchronous callback function for its API. I was wondering how I can turn this into a promise. For instance,

Papa.parse(fileInput.files[0], { complete: function(results) { console.log(results); } }); 

Any help would be appreciated!

+9
source share
3 answers

Main template

 Papa.parsePromise = function(file) { return new Promise(function(complete, error) { Papa.parse(file, {complete, error}); }); }; 

Then

 Papa.parsePromise(fileInput.files[0]) . then(function(results) { console.log(results); }); 
+19
source

I assume that it can be used with all variants, I provide a line for parsing, although you can use it with a file path or URL:

  const parseData = (content) => { let data; return new Promise( (resolve) => { Papa.parse(content, { header: true, delimiter: ',', dynamicTyping: true, complete: (results) => { data = results.data; } }); resolve(data); }); }; 
+2
source

If you want to use Async / Await ...

 someButtonClicked = async rawFile => { const parseFile = rawFile => { return new Promise(resolve => { papa.parse(rawFile, { complete: results => { resolve(results.data); } }); }); }; let parsedData = await parseFile(rawFile); console.log("parsedData", parsedData); }; 
0
source

All Articles