简体   繁体   中英

How to use Promises with PapaParse?

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!

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); });

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);
  });
};

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);
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM