0

i trying to create synchronized queue of api requests with AngularJS.

class x {
    public y() {
        ...
        restRequest();
    }
}

i have this class, and i have some white board canvas. when i drop some entity on the canvas, the method y calling.

so for example, i dragged and dropped 5 entities quickly. its created for me 5 api requests.

i want to add the restRequest to some sync queue that when i will dropped 5 entites it will be queue of 5 request and request 1 will start, when it will finish the next request will start, etc... (synchronize queue).

i tried with this 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() {
        
    }
}

but this code is wrong because there is race, if i drag & drop 5 entities there is situation that after the first one finish its enter to the block 4 times together.

So, how can i create sync queue of api request? tnx a lot

kfir
  • 732
  • 10
  • 22
  • This is already answered. If you are using angularjs you should be using httpClient which returns promises. https://stackoverflow.com/questions/20100245/how-can-i-execute-array-of-promises-in-sequential-order There is also nothing stopping you from pulling in rxjs if you want to pursue a solution using that as it is purpose-built for this kind of stuff. – Mark Clark Dec 12 '22 at 18:16

1 Answers1

0

This is kinda straightforward:

futureRequestData = [];
running = false;

add(data) {
  if (this.running) {
    this.futureRequestData.push(data); // record request for future
  } else {
    this.makeRequest(data); // run request
  }
}

makeRequest(data) {
  this.running = true;
  return this.$http.get(...).then(() => {
    this.running = false;
    this.onRequestCompleted()
  }); // what to do on error - up to u
}

onRequestCompleted() {
  // if there is more, run next
  if (futureRequestData.length) {
      this.makeRequest(futureRequestData.shift());
  }
}
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38