title: Lock in Javascript function
body: <p>I am making async calls to the server in a loop. Obviously ,it creates a race condition. Here is the code.</p>
  
  <pre><code>for (let i = 0; i &lt; arr.length; i++) {
    this.service.execute(arr[i]).pipe(takeUntil(this.ngUnsubscribe)).subscribe(response =&gt; {
  
      this.updateData(response); // Avoid race-condition here
    }, error =&gt; {
      //
    });
  }
  </code></pre>
  
  <p>I need a mechanism to avoid race-condition. But at the same time I do not want to chain async calls (I want them to work in parallel, only <code>updateData</code> function call should be sync.). Here is a sample how my code would look like if I could use Python-like lock mechanism:</p>
  
  <pre><code>for (let i = 0; i &lt; arr.length; i++) {
    this.service.execute(arr[i]).pipe(takeUntil(this.ngUnsubscribe)).subscribe(response =&gt; {
      // Assume lock is defined
      this.lock.acquire();
      this.updateData(response); // Avoid race-condition here
      this.lock.release();
  
    }, error =&gt; {
      //
    });
  }
  </code></pre>
  
  <p>As clearly seen from above code, only the calls of <code>updateData</code> are waiting for each other, not async calls made to the server. Is it possible to achieve something like that in Javascript, if so how can I do this?</p>