Abortable promises for API requests

In Time bounded server side rendering in Redux you can see that along with an API request promise, there is also an abort function. When called - that function will abort ongoing API request.

You may want an abortable promise for different reasons, but those used for asynchonous requests seem to benefit the most. One of such use-cases if canceling previous request if a new request was dispatched (otherwise you may first get new data and then the old one).

Abortable promises

Making a promise abortable is actually very easy. In this example we’re using jQuery.ajax for managing ajax requests.

function constructRequest(options) {
  const request = jQuery.ajax(options)

  const promise = new Promise((resolve, reject) => {
    request.then(function(data) {
      resolve(data)
    })

    request.fail(function(jqXHR, textStatus) {
      reject(textStatus)
    })
  })

  const abort = () => request.abort()

  return {abort, promise}
}

// Calling the function returns the abort function and a promise
const { abort, promise } = constructRequest({
  url: 'http://bumbu.me',
  method: 'GET'
})

So basically you have to wrap your async processor into a promise, and call its resolve and reject provided functions appropriately. Also provide a proxy into aborting mechanism.