不要忽视 AbortController
Today, I'd like to talk about one of the standard JavaScript APIs you are likely sleeping on. It's called AbortController
.
今天,我想谈谈一个标准的 JavaScript API,你可能对它不太熟悉。它被称为 AbortController
。
What is AbortController
?
AbortController
是什么?
AbortController
is a global class in JavaScript that you can use to abort, well, anything!
AbortController
是 JavaScript 中的一个全局类,您可以用它来中止任何操作!
Here's how you use it:
以下是使用方法:
1const controller = new AbortController()
1const controller = new AbortController()
Once you create a controller instance, you get two things:
创建控制器实例后,您将获得两个东西:
- The
signal
property, which is an instance ofAbortSignal
. This is a pluggable part you can provide to any API to react to an abort event, and implement it accordingly. For example, providing it to afetch()
request will abort the request; signal
属性是AbortSignal
的一个实例。这是一个可插拔的部分,您可以提供给任何API以对中止事件做出反应,并相应地实现它。例如,将其提供给fetch()
请求将中止该请求;- The
.abort()
method that, when called, triggers the abort event on thesignal
. It also updates the signal to be marked as aborted. - 调用
.abort()
方法会在signal
上触发abort事件。它还会将signal标记为已中止。
So far so good. But where is the actual abort logic? That's the beauty—it's defined by the consumer. The abort handling comes down to listening to the abort
event and implementing the abort in whichever way is suitable for the logic in question:
到目前为止一切顺利。但是实际的中止逻辑在哪里呢?这就是美妙之处——它由使用者定义。中止处理归结为监听abort
事件,并根据具体逻辑实现中止:
1controller.signal.addEventListener('abort', () => {
1controller.signal.addEventListener('abort', () => {
Let's explore the standard JavaScript APIs that support AbortSignal
out of the box.
让我们来探索一下标准的 JavaScript API,它们原生支持 AbortSignal
。
Usage
用法
Event listeners
事件监听器
You can provide an abort signal
when adding an event listener for it to be automatically removed once the abort happens.
您可以在添加事件监听器时提供一个中止signal
,以便在中止发生时自动删除它。
1const controller = new AbortController()
1const controller = new AbortController()
3window.addEventListener('resize', listener, { signal: controller.signal })
3window.addEventListener('resize', listener, { signal: controller.signal })
C...