Created
July 2, 2017 08:18
-
-
Save weihanglo/be4b9b31b545ee2605eb94bb415d79de to your computer and use it in GitHub Desktop.
Simple cancellable GET request promise
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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