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?
Promise.all()it accepts an array of promises and resolves/rejects only when all the promieses in the array have resolved or failed