Skip to content

Instantly share code, notes, and snippets.

@weihanglo
Created July 2, 2017 08:18
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 weihanglo/be4b9b31b545ee2605eb94bb415d79de to your computer and use it in GitHub Desktop.
Save weihanglo/be4b9b31b545ee2605eb94bb415d79de to your computer and use it in GitHub Desktop.
Simple cancellable GET request promise
/**
* GET request with a cancelable token
* @param {string} url - url to request
* @param {objecg} token - an object with a `cancel` function property.
* @return {Promise}
*/
export function cancellableGet (url, token) {
const xhr = new XMLHttpRequest()
return new Promise(function (resolve, reject) {
token.cancel = function () {
xhr.abort()
reject(`${url} has been cancelled!`)
}
xhr.onload = function(e) { resolve(xhr.responseText) }
xhr.onerror = reject
xhr.open('GET', url)
xhr.send()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment