Abort asynchronous task
6322 ワード
How to abort Asynchronous task
There’s a special built-in object for such purposes: AbortController
. It can be used to abort not only fetch
, but other asynchronous tasks as well.
The usage is very straightforward:
The AbortController object
Create a controller:let controller = new AbortController();
A controller is an extremely simple object.
let controller = new AbortController();
abort()
, signal
that allows to set event listeners on it. abort()
is called:controller.signal
emits the "abort"
event. controller.signal.aborted
property becomes true
. controller.signal
. controller.abort()
when needed. AbortError
, so we should handle it, e.g. in try..catch
.約束通りにFetch方法を管理する.
let controller = new AbortController();
let signal = controller.signal;
// The party that performs a cancelable operation
// gets the "signal" object
// and sets the listener to trigger when controller.abort() is called
signal.addEventListener('abort', () => alert("abort!"));
// The other party, that cancels (at any point later):
controller.abort(); // abort!
// The event triggers and signal.aborted becomes true
alert(signal.aborted); // true
with the fetch()// abort in 1 second
let controller = new AbortController();
setTimeout(() => controller.abort(), 1000);
try {
let response = await fetch('/article/fetch-abort/demo/hang', {
signal: controller.signal
});
} catch(err) {
if (err.name == 'AbortError') { // handle abort()
alert("Aborted!");
} else {
throw err;
}
}
Reference
この問題について(Abort asynchronous task), 我々は、より多くの情報をここで見つけました https://velog.io/@hqillz/Abort-asynchronous-taskテキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol