20

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!

thehelpofgreat
  • 201
  • 1
  • 2
  • 3

3 Answers3

36

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); });
  • This works, and thank you, but I don't understand what complete and error are doing. Could you please explain? – Kyouma Mar 26 '20 at 02:06
  • 2
    @Kyouma `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`. – Pierre Dec 06 '20 at 16:52
  • Nice, great job! – unknown Apr 28 '22 at 13:44
8

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);
  };
nllerandi
  • 99
  • 1
  • 3
  • 2
    You should move the `parseFile` "helper" function outside of `someButtonClicked`, it's really independent from the use of `async`/`await` there. – Bergi Oct 30 '20 at 16:36
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);
      }
    });
    
  });
};
Abhishek Parmar
  • 145
  • 1
  • 11