0

I am making async calls to the server in a loop. Obviously ,it creates a race condition. Here is the code.

for (let i = 0; i < arr.length; i++) {
  this.service.execute(arr[i]).pipe(takeUntil(this.ngUnsubscribe)).subscribe(response => {

    this.updateData(response); // Avoid race-condition here
  }, error => {
    //
  });
}

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 updateData function call should be sync.). Here is a sample how my code would look like if I could use Python-like lock mechanism:

for (let i = 0; i < arr.length; i++) {
  this.service.execute(arr[i]).pipe(takeUntil(this.ngUnsubscribe)).subscribe(response => {
    // Assume lock is defined
    this.lock.acquire();
    this.updateData(response); // Avoid race-condition here
    this.lock.release();

  }, error => {
    //
  });
}

As clearly seen from above code, only the calls of updateData 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?

3
  • 1
    Take a look at Promise.all() it accepts an array of promises and resolves/rejects only when all the promieses in the array have resolved or failed Commented Feb 18, 2019 at 11:36
  • But it still executes a couple of functions at the same time which is what I want to avoid Commented Feb 18, 2019 at 11:38
  • There is no built-in feature I know of which does it. My first approach would be class for managing the locks. A quick search brought me to async-lock. Maybe thats what you need. Commented Feb 18, 2019 at 11:57

1 Answer 1

1

Javascript execution is always single-threaded, so unless your updateData function contains async calls itself, there is no race condition.

Sign up to request clarification or add additional context in comments.

2 Comments

It does not contain any async calls. Does that mean I can safely call the same function from different environments?
It depends what you mean by different environments. If they're all happening inside the same program/webpage/script, then yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.