0

I've written this function for an Angular app that is intended to get the contents of an Observable this.lines$ and return it as an array within an object. It seems to work but I wonder if there could be occasions when it won't?:

  public getOutput(): { lines: Line[] } {
    const linesArray: Line[] = [];
    this.lines$
      .pipe(
        map(lines => {
          lines.forEach(line =>
            lines.push({
              lineNumber: line.lineNumber,
              variables: line.variables,
            })
          );
        }),
        take(1)
      )
      .subscribe();
    return {
      lines: linesArray
    };
  }

My main concern is that the return at the end of the function could happen before the contents of the Observable's subscription are run. Could that be the case? Is there a better way of achieving this?

eebsie
  • 396
  • 5
  • 18
  • 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) – ruth Mar 12 '21 at 12:40
  • This is not how async call works. By the time the `return` is executed, the `linesArray` variable might not be defined yet. You need to return the observable and subscribe where the data is required. All statements that directly depend on the data from the observable _must_ be inside the subscription. See [here](https://stackoverflow.com/q/14220321/6513921) for more info on async requests. – ruth Mar 12 '21 at 12:41

0 Answers0