How to cancel Promise.all () in Angular 2?

I currently have a registration process, and each subsequent click produces Promise.all (), which causes a lot of HTTP requests. If the client runs very quickly (click the following buttons very quickly), the entire HTTP request is created and this will ruin my application.

Is there a way to cancel Promise.all () so that if they click next and the previous Promise.all () is still working, can I just cancel it?

+4
source share
3 answers

You can wait for the promises to finish, but you cannot cancel them.

You can disable the next next button until all of them are completed.

<button [disabled]="completed">Next</button>

+4

, " Promise.all()" ", , Promise.all(), "....

Promises , .

. , promises , :

  • , raw
  • .

.

"-" .

- , - - .

function BatchCanceller() {
    // Return a function, which accepts an array of promises and returns an aggregated promise.
    // Use the returned function like $q.all().
    var dfrd;
    return function(promises) {
        if(dfrd) {
            dfrd.reject(new Error('cancelled')); // reject previous batch
        }
        dfrd = $q.defer();
        // Preparation; ensure that `promises`, if all are successful, resolve `dfrd`.
        $q.all(promises).then(dfrd.resolve);
        // Now include `dfrd` in a super-aggregation of `promises`
        return $q.all(promises.concat(dfrd.promise)) // Will the aggregated `promises` resolve before another batch causes `dfrd.reject()`?
        .then(function(results) {
            // Yay! the aggregated `promises` won out.
            return results.splice(0, results.length-1); // remove the unwanted extra result.
        }); // no need to handle error here
    };
}

var batchCanceller = new BatchCanceller();

var promises = [/* whatever */];
batchCanceller(promises).then(function(results) {
    console.log(results);
}).catch(function(error) {
    console.log(error); // message is "cancelled" if another `batchCanceller(promises)` is executed before the previous one resolves.
});

, , BatchCanceller() Angular factory.

0

, switchMap debounceTime, -

export class MyComponent implements OnInit {
  actions: Observable<any[]>;
  private signals = new Subject<string>();
  constructor() {}

  submit(signal: string): void {
    this.signals.next(signal);
  }

  ngOnInit(): void {
    this.actions = this.signals
      .debounceTime(300)        
      .distinctUntilChanged()
      .switchMap(signal => {
         // make http calls with the signal e.g
         // return this.service.getAction(signal)
      })
      .catch(error => {
        // handle error
      });
  }
}

https://angular.io/docs/ts/latest/tutorial/toh-pt6.html#!#-_observable-s

The good thing about it switchMapis that it will cancel any HTTP requests in flight if another signal passes. At the same time, if your server does not handle canceled requests, this helps a little.

0
source

Source: https://habr.com/ru/post/1666026/


All Articles