0

I am working with Typescript in Ionic 4. My problem is, that the part of the inner function is processed after the outer part, though the outer part of code is written under the inner part. That is a big problem for me, because the return value is always wrong. If I want the right value, I have to call the function twice. Here is my code, which you can also see in the linked picture here. The function only reads a json file and returns the json object.

ReadFile(filename: string, fileFunktion: string) {
    this.http.get(filename).subscribe((data) => {
      this.data = data;
    });
    return this.data;
      }

Can you give me advice, how to fix this problem? Thank you :)

  • 1
    You need to read up an asynchronous function execution. There are a lot of answers all over covering this topic. – bryan60 Feb 08 '20 at 18:57
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – bryan60 Feb 08 '20 at 18:58

1 Answers1

0

The subscribe function is asynchronous, in a similar way to how promises are asynchronous. So your function starts the http request which runs in the background. Whilst it is running, the program then carries on so it returns whatever this.data happens to be set to.

How to fix it depends on how you want to handle the async nature. One easy way is to convert the observable to a promise and use async/await so you get something like:

async ReadFile(filename: string, fileFunktion: string) {
    this.data = await this.http.get(filename).toPromise()
    return this.data
}

ReadFile is an async function so it always returns a promise so you would need to use await when calling it:

await ReadFile('foo', 'barr')

Mixing promises and observables isn't the greatest of things but it can help as an easy way to get things going whilst you decide the best way forward.

matt helliwell
  • 2,574
  • 16
  • 24