title: How to prevent parallel execution of asynchronous init method in JavaScript?
body: <p>I want to preload a search index in JavaScript as soon as the page is loaded, so that the user may not have to wait for it to be build. I know JavaScript is single threaded and a lock is normally not required, but I am not sure if the following code is sufficient:</p>
  
  <pre><code>class Index
  {
    constructor()
    {
      this.index = null;
    }
  
    async init()
    {
      this.index = await queryDatabase();
    }
  
    async search(input)
    {
      if(!this.index) {await this.init();}
      return this.index.query(input);
    }
  }
  
  Index index = new index();
  index.init(); // preload
  myButton.addEventListener("click",console.log(index.search()));
  </code></pre>
  
  <p>Can it happen that a user clicks on myButton before init() is finished and that init is called twice? If not, how can I prevent that in the best way?</p>