I am attempting to develop a synchronized queue for API requests using AngularJS.
class x {
public y() {
...
restRequest();
}
}
I have this class, along with a whiteboard canvas. When I drop an entity onto the canvas, the method 'y' is called.
For example, if I quickly drag and drop 5 entities, it generates 5 API requests for me.
I wish to implement the 'restRequest' in a synchronous queue so that when I drop 5 entities, it will form a queue of 5 requests where request 1 will start first, followed by the next request upon completion, and so on (synchronized queue).
I attempted to achieve this with the following code:
class x {
private queue: object = {};
public y() {
const uniqueId: number = Date.now();
let queueIsEmpty = _.isEmpty(this.queue);
const func = setInterval(() => {
if(queueIsEmpty) {
this.queue[uniqueId] = true;
clearInterval(func);
restRequest();
}
queueIsEmpty = _.isEmpty(this.queue);
}, 1000);
}
private restRequest() {
}
}
However, this approach is incorrect as there is a race condition – after the first request finishes, it can enter the block four times altogether for the remaining queued requests.
So, how can I create a synchronized queue of API requests? Thank you.