Last active
September 26, 2024 19:50
-
-
Save scottymeyers/bd38f536e191c0baf50cc6008add6764 to your computer and use it in GitHub Desktop.
AbortController
This file contains hidden or 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
"use-strict"; | |
////////// Event listeners ////////// | |
const eventController = new AbortController(); | |
eventController.signal.addEventListener("abort", (s) => { | |
console.log("aborted event listener controller", { | |
reason: eventController.signal.reason, | |
}); | |
}); | |
// the instance | |
eventController.signal; | |
window.addEventListener("resize", (e) => console.log(e), { | |
// listener will be removed when the given AbortSignal object's abort() method | |
// is called if not specified, no AbortSignal is associated with the listener | |
signal: eventController.signal, | |
}); | |
// method that triggers the abort event | |
// (supply a reason as an optional argument to abort) | |
eventController.abort("testing"); | |
////////// Fetch requests ////////// | |
function makeRequest() { | |
const fetchController = new AbortController(); | |
const request = fetch("https://jsonplaceholder.typicode.com/todos/1", { | |
method: "GET", | |
signal: fetchController.signal, | |
}); | |
return { request, fetchController }; | |
} | |
const req = makeRequest(); | |
req.fetchController.signal.addEventListener("abort", () => { | |
console.log("aborted fetch request controller"); | |
}); | |
req.fetchController.abort(); | |
// you can abort if the request takes longer than a specified length of time: | |
const request = fetch("https://jsonplaceholder.typicode.com/todos/1", { | |
method: "GET", | |
signal: AbortSignal.timeout(10000), | |
}); | |
// you can also use AbortSignal.any([...]) to handle multiple promises, | |
// example given is a public + internal AbortControllers where the internal | |
// one has the ability to abort the public one if it choses to do so | |
////////// STREAMS ////////// | |
(async () => { | |
const stream = new WritableStream({ | |
write(chunk, controller) { | |
controller.signal.addEventListener("abort", () => { | |
console.log("aborted stream controller"); | |
}); | |
}, | |
}); | |
const writer = stream.getWriter(); | |
await writer.abort(); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment