-1

Angular Service

this.sendCommand = function (someData) {

                URL = myURL;
                return $http({
                    method: 'POST',
                    url: URL,
                    data: someData
                }).then(function (response) {
                    return response.data;
                }).catch(function (error) {
                    console.log(error)
                });
            };

Use Case: User can send multiple commands by clicking on a button. For example, request 2 should not return response until request 1 response is fulfilled. How do I make synchronous call using above snippet, so that even if user clicks on a button multiple times, the request being sent will be served in queue ?

Slimshadddyyy
  • 4,085
  • 5
  • 59
  • 121
  • Why should the use case require synchronous requests? – a better oliver Dec 13 '16 at 09:39
  • @HardikVaghani: The $http functions already return a Promise object themselves. This means there’s really very little need to create a new deferred and pass the associated promise back, much less having to handle the resolving and rejecting code as part of your service logic. – Slimshadddyyy Dec 13 '16 at 09:48
  • @zeroflagL: coz the component receiving the request is able to serve single request at a time. – Slimshadddyyy Dec 13 '16 at 09:48
  • I understand that, but the request itself doesn't have to be synchronous. – a better oliver Dec 13 '16 at 10:00

2 Answers2

0

I think it could be handled better with a boolean variable. As javascript is single threaded you could just create a variable 'isWaitingForResponse' and add an if to send the request only if there is no other in progress.

this.sendCommand = function (someData) {
    if (!this.isWaitingForResponse) {
        this.isWaitingForResponse = true; 
        // do request
        .then(
            this.isWaitingForResponse = false;
        );
    } else {
        // don't send request
    }
};

If you really want to queue the requests you could use a javascript: queue stackoverflow queue question. Then your code would look like this:

this.sendCommand = function (someData) {
    if (!this.isWaitingForResponse) {
        this.isWaitingForResponse = true; 
        // do request
        .then(
            this.isWaitingForResponse = false;
            // check if there is a request in a queue
            // if there is: invoke this.sendCommand
        );
    } else {
        // don't send request
        // put request in a queue
    }
};
Community
  • 1
  • 1
Paweł Kozikowski
  • 1,025
  • 2
  • 11
  • 23
0

You can use a spinner to block user clicking the button before the previous request is completed.

salix
  • 846
  • 6
  • 13