1

I am getting undefined value when calling enterUsingCSV() directly. The function works correctly when called inside GetDataExcel(). Can anyone explain what is happening?

//// 
GetDataExcel(col: number) {
        this.papa.parse(this.file, {
            complete: async (result: any) => {
                let cc = result.data[1][col]
                //console.log(cc)
                return cc
            }
        })
    }

///
 enterUsingCSV(column:number){
    let value = this.GetDataExcel(column)
    console.log(value)
    // this.enterText("username", "id", value)

  }

//// 
e.enterUsingCSV(2);
av376
  • 15
  • 2

1 Answers1

1

According to the documentation, when we call Papa.parse with a local file, the parse method does not return anything. Instead, the results are provided asynchronously to a callback function. That's exactly the behavior you're seeing.

GetDataExcel(col: number) {
  // The result value will always be undefined here,
  // because when we pass a local file to parse,
  // parse does not return anything.
  const result = this.papa.parse(this.file, {
    complete: async (result: any) => {
      // Instead, the results are passed to this complete callback.
      let cc = result.data[1][col];
      console.log(cc);
      // There is no point in returning cc here, 
      // because there is nothing waiting to receive the return value.
      return cc;
    }
  });
}

enterUsingCSV(column:number) {
  // The value here will also be undefined. There are two reasons for that. 
  // First, the GetDataExcel method isn't returning anything. Second, even if 
  // it did return the result constant, the result constant is always undefined, 
  // because Papa.parse does not return anything when we pass it a local file. 
  let value = this.GetDataExcel(column);
  console.log(value);
}

e.enterUsingCSV(2);

Here is the relevant documentation:

Parse local files

Papa.parse(file, config)

file is a File object obtained from the DOM.

config is a config object which contains a callback.

Doesn't return anything. Results are provided asynchronously to a callback function.

Shaun Luttin
  • 133,272
  • 81
  • 405
  • 467
  • thanks for your input, solved my problem by GetDataExcel(col: number){ let results = this.papa.parse(this.file, { }); let f = results.data[1][col] let CombData = f return CombData } – Francis Teo Mar 11 '19 at 05:08
  • You're welcome. I'm glad that my answer was useful, and that it helped you to solve the problem. Well done. – Shaun Luttin Mar 11 '19 at 15:48