title: Efficient way of waiting for a variable to be set?
body: <p>I am looking for an efficient way of checking if a variable has been set in my Angular application, so I don't have to keep checking if it has been set. I have a service that loads all products into a variable, when the user first requests the page. Example:</p>
  
  <pre><code>export class ProductService {
      public products: Product[];
  
      constructor(private http: HttpClient) { }
  
      init(): any {
          if (!this.products) {
              this.http.get&lt;Product[]&gt;("https://my-api.com/GetAllProducts").subscribe(products =&gt; {
                  this.products = products;
              });
          }
      }
  }
  </code></pre>
  
  <p>I then call this simply saying <code>productService.init()</code> in my <code>app.component.ts</code> file, which makes sure it initializes the products  for later use. However, I also have a method that grabs a product from a product ID:</p>
  
  <pre><code>getProductFromProductId(productId: string) {
      return this.products.find(x =&gt; x.id === productId);
  }
  </code></pre>
  
  <p>This <code>getProductFromProductId</code> method gets called on every page at least once. Let's imagine the <code>init()</code> method takes 2000ms to load, because there are a lot of products, calling <code>getProductFromProductId()</code> would fail because <code>products</code> is not set yet. To fix this, I could do something like:</p>
  
  <pre><code>getProductFromProductId(productId: string) {
      if(!this.products) {
          setTimeout(() =&gt; {
              console.log("Products not loaded yet");
              getProductFromProductId(productId);
          }, 10);
      } else {
          return this.products.find(x =&gt; x.id === productId);
      }
  }
  </code></pre>
  
  <p>The above code checks if <code>products</code> has been set every 10ms. If not, it simply calls the method again.</p>
  
  <p>However, let's imagine I have 10 methods in this service. That's a lot of "<strong>not loaded yet</strong>" possibilities, which means I would have to repeat the same code 10 times (or move it to a function, but you get the point). The biggest issue is that <code>getProductFromProductId</code> and <code>init</code> are both called at the same time, so we need to wait for <code>init</code> to finish, basically.</p>
  
  <p>Is there a better way of doing this?</p>