How to block during a callback pattern?

export default class Counter {
  parsedData: any[];

  constructor(private files: string[]) {
    this.buildConfig(); #1 --------------
  }


  buildConfig = () => ({
    header: true,
    skipEmptyLines: 'greedy' as 'greedy',
    preview: 4,
    complete: this.printAndSave
  })

  printAndSave({ errors, data }) { #2 --------------
    if (errors.length) {
      console.log(`errors`, errors);
    }
    if (Object.keys(data).length) {
      console.log('=============================================');
      console.log(`data`, data);
      console.log('=============================================');

      this.parsedData = data;
    }
  }

  public parseAndPrint() { // #1 --------------
    // let parsedStrings: string[];
    this.files.forEach(file => Papa.parse(file, parseConfig));
  }

Bottom function starts the call stack. I can see a problem with printAndSave not assigning to parsedData before I use parsedData syncronously in later method calls.

How can I block this process so other methods don’t work with parsedData when it’s undefined? I’m guessing it needs to be promisified but I’m not sure how.

Hello!

Couldn’t you just initialize it to an empty array? Another option would be to use a flag and hide the parsedData within a getter:

export default class Counter {
  private parsedData: any[] = [];
  private isParsed: bool = false;

  constructor(private files: string[]) {
    this.buildConfig(); #1 --------------
  }

  buildConfig = () => ({
    header: true,
    skipEmptyLines: 'greedy' as 'greedy',
    preview: 4,
    complete: this.printAndSave
  })

  printAndSave({ errors, data }) { #2 --------------
    if (errors.length) {
      console.log(`errors`, errors);
    }
    if (Object.keys(data).length) {
      console.log('=============================================');
      console.log(`data`, data);
      console.log('=============================================');

      this.parsedData = data;
      isParsed = true;
    }
  }

  public parseAndPrint() { // #1 --------------
    // let parsedStrings: string[];
    this.files.forEach(file => Papa.parse(file, parseConfig));
  }

  get theData(): any[] {
    if (this.isParsed) {
      return this.parsedData;
    }

    return [];
  }
}

But I think there may be a better alternative to solve the problem if you explain what you’re trying to do :slight_smile:.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.