Last active
May 22, 2016 15:59
-
-
Save domenic/9daa9510efec80827b3d4f9ae372464d to your computer and use it in GitHub Desktop.
Cancel token discussion points
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
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(); | |
}); | |
}); | |
} |
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
// 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