PolymerElements / iron-ajax

Easily make ajax requests
https://www.webcomponents.org/element/PolymerElements/iron-ajax
127 stars 113 forks source link

Requests that can be canceled or delayed before in-flight #229

Open AimForNaN opened 8 years ago

AimForNaN commented 8 years ago

Similar to that of iron-form's presubmit event, I think it would be useful for iron-ajax to be able to allow intercepting the request before sending or for us to have a say on whether or not to allow sending the request when a request is generated. The idea mentioned by cdata, "a boolean attribute that causes in-flight requests to be automatically cancelled when new requests are made," would be awesome! Even allowing for an async-sync hybrid feature, where each request is queued and not sent until the previous request received a response.

mc-izzy commented 6 years ago

Has this ever been done? It would be nice to be able to have an auto cancel of in-flight requests if another is right on it's heels or ahead and out of order.

stramel commented 6 years ago

You should be able to cancel before in-flight by using the iron-ajax-presend event.

this.$.ajax.addEventListener('iron-ajax-presend', (e) => {
  if (condition) {
    e.preventDefault();
    e.stopPropagation();
  }
});

if you want to cancel a previous in-flight request when a new request is made, you could do so like this:

this.$.ajax.addEventListener('iron-ajax-presend', (e) => {
  // Prevent send of current request based on condition
  if (condition) {
    e.preventDefault();
    e.stopPropagation();
  }

  // Cancel the previous request using `iron-request#abort`
  this.$.ajax.activeRequests[0].abort();
});