0
loadcsv(file: File): string[] {
  let csvRecordsArray: string[];
  this.parse(file).then((p) => {
    console.log(p);
    csvRecordsArray = p as string[];
  });
  console.log('mydata', csvRecordsArray);
  return csvRecordsArray;
}

console.log inside the then prints the data I need. Nothing wrong with the Promise. However, since it does not block my second console.log has undefined in csvRecordsArray. So I read up on Promises and learnt that I need to await. As soon as I type async to make loadcsv async ts lint says:

Type 'string[]' is not a valid async function return type in ES5/ES3 because it does not refer to a Promise-compatible constructor value.

Please help me get out of this tailspin.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Gullu
  • 3,477
  • 7
  • 43
  • 70
  • You cannot make a function that calls an asynchronous function and returns the result from the future immediately. You need to return a promise for the string array. – Bergi Sep 28 '18 at 15:49
  • Everyone who voted duplicate didn't read the question. @Bergi you're too quick on the draw. – Evert Sep 28 '18 at 15:57
  • @Evert You mean this question is only about the type error (from code that wasn't even shown)? I think the OPs problem is his misunderstanding of async code, surfaced in the attempt to assign `csvRecordsArray = p` in the callback. (And yes, it was only me who voted duplicate, that comes from my shiny polished mjölnir :P) – Bergi Sep 28 '18 at 16:03
  • @Bergi you should err on the side of caution. You obviously have been super helpful in the community, but quickly closing questions without explanation is what gives SO a bad name for newcomers. – Evert Sep 28 '18 at 16:08
  • @Evert I even commented. What explanation do you think is missing? Btw, if you like I can reopen the question – Bergi Sep 28 '18 at 16:14
  • @Bergi I think OP has their answer, so no need. – Evert Sep 28 '18 at 16:19

2 Answers2

1

You can change the implementation of your loadcsv function by making it async. For that, you'll have to await the function call to this.parse.

Also since async functions are expected to return a Promise, you'll have to change the return type of your function to Promise<string[]>

Change your implementation like this:

async loadcsv(file: File): Promise<string[]> {
  let csvRecordsArray: string[];
  csvRecordsArray = await this.parse(file);
  console.log('mydata', csvRecordsArray);
  return csvRecordsArray as string[];
}
SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
0

If your function is an async function because you need to use await, those functions always return a Promise.

So the correct signature for this is:

loadcsv(file: File): Promise<string[]>  {
}
Evert
  • 93,428
  • 18
  • 118
  • 189