How to use Promises with PapaParse?

。_饼干妹妹 提交于 2019-11-30 08:52:17

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);
  };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!