How to use Promises with PapaParse?
Asked Answered
C

3

23

PapaParse has an asynch callback function for its API. I was wondering how I can convert it to a promise. For eg:

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

Any help would be appreciated!

Crutch answered 13/7, 2015 at 4:43 Comment(0)
P
38

The basic pattern is

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); });
Pyramidal answered 13/7, 2015 at 4:59 Comment(3)
This works, and thank you, but I don't understand what complete and error are doing. Could you please explain?Ruffin
@Ruffin complete is the Promise's resolve function and error is the reject function, they are being used as the callback functions on complete and error for Papa.parse.Emeritaemeritus
Nice, great job!Hexagram
H
9

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);
  };
Hydrosol answered 21/6, 2019 at 15:53 Comment(1)
You should move the parseFile "helper" function outside of someButtonClicked, it's really independent from the use of async/await there.Brueghel
H
0

I guess it can be used with all kind of variations, I am providing the string to parse although you can use it with 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);
      }
    });
    
  });
};
Hudson answered 5/2, 2018 at 3:13 Comment(3)
This is plain wrong and does not work when the complete callback is asynchronous. You resolve the promise before data gets assigned.Brueghel
ohh sorry that was typo from my sideHudson
But if you do it properly, you don't need that let data at allBrueghel

© 2022 - 2024 — McMap. All rights reserved.