Skip to content

Instantly share code, notes, and snippets.

@domenic
Last active May 22, 2016 15:59
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 domenic/9daa9510efec80827b3d4f9ae372464d to your computer and use it in GitHub Desktop.
Save domenic/9daa9510efec80827b3d4f9ae372464d to your computer and use it in GitHub Desktop.
Cancel token discussion points
function xhrAdapted(url, { cancelToken } = {}) {
const xhr = new XMLHttpRequest();
return new Promise((resolve, reject, cancel) => {
xhr.addEventListener("load", () => resolve(xhr.responseText));
xhr.addEventListener("error", () => reject(new Error("could not XHR")));
if (!cancelToken) return;
cancelToken.promise.then(reason => {
cancel(reason);
xhr.abort();
});
});
}
// With "tasks"
startSpinner();
const p = fetch(url)
.then(r => r.json())
.then(data => fetch(data.otherURL))
.then(r => r.text())
.then(text => updateUI(text))
.catch(err => showUIError())
.finally(stopSpinner);
cancelButton.onclick = () => p.cancel();
// With cancel tokens:
startSpinner();
let cancel;
const cancelToken = new CancelToken(c => cancel = c);
fetch("url", { cancelToken })
.then(r => r.json({ cancelToken }))
.then(data => fetch(data.otherURL, { cancelToken }))
.then(r => r.text({ cancelToken }))
.then(text => updateUI(text))
.catch(err => showUIError())
.finally(stopSpinner);
cancelButton.onclick = cancel;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment