Skip to content

Instantly share code, notes, and snippets.

@stramel
Created September 12, 2018 03:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stramel/edae32a037489709e9b2dd2b560fdfa7 to your computer and use it in GitHub Desktop.
Save stramel/edae32a037489709e9b2dd2b560fdfa7 to your computer and use it in GitHub Desktop.
Abortable Fetch helper function

Abortable Fetch helper

Usage

import fetch, { ABORT_ERROR } from 'custom-fetch'

const abortableFetch = makeAbortable(fetch) // Defaults to `window.fetch` if no fetch is passed

const request = abortableFetch('/URL') // Returns an object with a `promise` and an `abort` property

// To abort
request.abort()

// To get response
const response = await request.promise

Example Implementation (Auto-cancelling Fetch)

let request
const getData = async () => {
  if (request && request.abort) {
    request.abort()
    request = undefined
  }

  request = abortableFetch('/URL')

  try {
    const data = await request.promise
    console.log(data)
  } catch (ex) {
    if (ex.name !== ABORT_ERROR) {
      console.error(ex)
    } else {
      console.log('Aborted')
    }
  }
}
/**
* Makes a fetch function abortable
* @param {function} fetch
* @return {object} - Has an `abort` and a `promise` property
*
* https://developers.google.com/web/updates/2017/09/abortable-fetch
* https://github.com/mo/abortcontroller-polyfill#readme
*/
export const makeAbortable = (fetch = window.fetch) => {
return (input, { controller, signal, ...options } = {}) => {
if ('AbortController' in window && typeof input === 'string') {
controller = controller || new AbortController()
options.signal = signal || controller.signal
}
return {
promise: fetch(input, options),
abort: () => controller && controller.abort(),
}
}
}
export const ABORT_ERROR = 'AbortError'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment