当前位置:网站首页>Interrupt operation: abortcontroller learning notes
Interrupt operation: abortcontroller learning notes
2022-06-30 02:49:00 【Zhou Junjun's personal blog】
Front end interview usually likes to ask :
In my opinion 《 Use AbortController End fetch request 》, I thought it was very detailed , So refine your notes :
AbortController Background introduction
In the current browser , There are two main ways to send a request :XMLHttpRequest and fetch.XMLHttpRequest This interface has existed in browsers for a long time ,fetch It is ES2015 Features introduced .
XMLHttpRequest Can be terminated halfway through the request (abortable). for instance
let xhr = new XMLHttpRequest();
xhr.method = 'GET';
xhr.url = 'https://slowmo.glitch.me/5000';
xhr.open(method, url, true);
xhr.send();
// Abort the request at a later stage
abortButton.addEventListener('click', function() {
xhr.abort();
});fetch Termination requests are not supported at the beginning of the import .Github The first time stay 2015 It ends in fetch The proposal requested issue appear . stay fetch There are many solutions to this problem beyond the specification , image cancelable-promises And others hacks.
finally , General purpose AbortController and AbortSignal API Come out . The API stay DOM standard In the definition of , Not defined in the language specification .
What is? AbortController
AbortController It's a DOM API.MDN The introduction to it is AbortController Interface represents a controller object , Allows one or more... To be terminated as needed Web request .
AbortController Can be used in fetch and addEventListener, Used to discard requests and listeners respectively .
See the official website for details :
https://developer.mozilla.org/zh-CN/docs/Web/API/AbortController/AbortController
"AbortController" | Can I use... Support tables for HTML5, CSS3, etc
DOM file There is a passage in :
although Promise No built-in termination algorithm is provided (aborting mechanism), But many use them API Need to terminate semantics .AbortController Provide a abort() Methods to support these requirements , This method is used to switch the corresponding AbortSignal Object state . Those who want to support the termination function API Acceptable AbortSignal object , And determine the execution process based on its status .
AbortController It consists of two parts :abort-signal and abort-controller, The architecture is as follows :

The red part is what we need to focus on , Because they will be directly reflected in practical application
AbortSignal Source code interpretation
AbortSignal The source code parsing
...
export default class AbortSignal extends EventTarget<Events, EventAttributes> {
/**
* from abortedFlags Get the current AbortSignal example aborted state
*/
public get aborted(): boolean {
const aborted = abortedFlags.get(this)
if (typeof aborted !== "boolean") {
throw new TypeError(
`Expected 'this' to be an 'AbortSignal' object, but got ${
this === null ? "null" : typeof this
}`,
)
}
return aborted
}
}
// Set up abort Custom events
defineEventAttribute(AbortSignal.prototype, "abort")
...
/**
* Create a AbortSinal example , And set up aborted Status as false, Deposit in abortedFlags in , Simultaneous binding abort Event properties
*/
export function createAbortSignal(): AbortSignal {
const signal = Object.create(AbortSignal.prototype)
EventTarget.call(signal)
abortedFlags.set(signal, false)
return signal
}
/**
* Set up AbortSinal example aborted Status as true, Trigger at the same time abort Listen for event callbacks
*/
export function abortSignal(signal: AbortSignal): void {
if (abortedFlags.get(signal) !== false) {
return
}
abortedFlags.set(signal, true)
signal.dispatchEvent<"abort">({ type: "abort" })
}
...AbortSignal Inherit EventTarget( Third party dependency package , The function is to give instances to listen to custom events , It will help you solve compatibility problems addEventListener/onXX/dispatchEvent),AbortSignal The custom abort Monitoring events
AbortSignal.aborted(): Get whether the current instance has been started abort Monitoring events .
abortedFlags:map type , Whether the for storing each instance has been started abort Monitoring events , The default is false(createAbortSignal Set when creating an instance ), call abortSignal Function will be set to true
createAbortSignal(): Building functions , The initialization instance object is false, binding abort Monitoring events ( You need to set it yourself abort Listen for callback events )
abortSignal(instance): Set the current instance state to ture, Trigger at the same time abort Listen for callback events
AbortController The source code parsing
...
export default class AbortController {
/**
* Constructors , Create a AbortSignal Instance and save it to signals in
*/
public constructor() {
signals.set(this, createAbortSignal())
}
/**
* from signals Get the current AbortSignal example
*/
public get signal(): AbortSignal {
return getSignal(this)
}
/**
* First from signals Get the current AbortSignal example , Then set the instance aborted Status as true, Trigger abort Listen for callback events
*/
public abort(): void {
abortSignal(getSignal(this))
}
}
...AbortController Constructor will call createAbortSignal establish AbortSignal Instance and save it into a Map Type of signals in .
abort() Method will call abortSignal function , The parameter passed in is from signals Out of AbortSignal example
signal() The function of the method is from signals Remove from AbortSignal example
Reference source code :
AbortController addEventListener
as everyone knows , if necessary removeEventListenr(type, callback), its callback It has to be with addEventListener Is the same function reference , In some business scenarios , We don't want to write more functions. We can use signal To control .
for example , Set a listener when clicking the mouse , Monitor the mouse movement in the listener , Release the mouse to close the listener :
document.addEventListener('mousedown', callback);
document.addEventListener('mouseup', callback2);
function callback (e) {
document.addEventListener('mousemove', callback3);
}
function callback2 (e) {
document.removeEventListener('mousemove', callback3);
}
function callback3(event) {}If it is rewritten into AbortController How to write it? ?
const controller = new AbortController();
function callback (e) {
document.addEventListener('mousemove', (e) => {
},{
signal: controller.signal
});
}
document.addEventListener('mousedown', callback);
document.addEventListener('mouseup', controller.abort);Advanced
Each request , Will recreate a AbortSignal Instance ?
answer : Yes
signals and abortedFlags All are Map type , Each request creates an instance , As time goes on and requests increase , How to prevent cache avalanche ?
answer :signals and abortedFlags Exactly WeakMap type , and WeakMap Follow Map It's going to make a difference ,WeakMap The key of can only be a reference to an object , When the garbage collection mechanism is executed , Will detect WeakMap Whether the key of is referenced , If not quoted , The key pair will be deleted , And automatically recycle , To prevent cache avalanche problems .
AbortSignal How to have the ability to listen to events ?
answer : It doesn't have event handling capabilities by itself , It inherits a EventTarget Class to enable it to listen and handle events
Reference article :
An interruptible request fetch Principle analysis and application of An interruptible request fetch Principle analysis and application of - You know
[ translate ] Use AbortController End fetch request [ translate ] Use AbortController End fetch request - Nuggets
An interruptible request fetch Principle analysis and application of ( Previous notes ) https://github.com/ctq123/blogs/issues/9
AbortController Use scenarios to explore AbortController Use scenarios to explore - Simple books
Reprint This station article 《 Interrupt operation :AbortController Learning notes 》,
Please indicate the source : Interrupt operation :AbortController Learning notes - html5 - Zhou army's personal website
边栏推荐
- Intel-Hex , Motorola S-Record 格式详细解析
- 原生JS怎么生成九宫格
- A quick look at the statistical data of 23 major cyber crimes from 2021 to 2022
- JMeter obtains cookies across thread groups or JMeter thread groups share cookies
- FDA ESG规定:必须使用数字证书保证通信安全
- 什么是X.509证书?X.509证书工作原理及应用?
- Pytorch学习(二)
- 公司电脑强制休眠的3种解决方案
- Shell Sort
- 什么是证书透明度CT?如何查询CT logs证书日志?
猜你喜欢

HTA introductory basic tutorial | GUI interface of vbs script HTA concise tutorial, with complete course and interface beautification

2.< tag-动态规划和0-1背包问题>lt.416. 分割等和子集 + lt.1049. 最后一块石头的重量 II

Steam elements hidden in science and Technology Education

Unity3d ugui force refresh of layout components

Intel-Hex , Motorola S-Record 格式详细解析

What is digicert smart seal?

在php中字符串的概念是什么

什么是证书透明度CT?如何查询CT logs证书日志?

Unity3D UGUI强制刷新Layout(布局)组件

IDEA 远程调试 Remote JVM Debug
随机推荐
Unity3D UGUI强制刷新Layout(布局)组件
Threejs mirror case reflector create mirror + house construction + small ball movement
How to set password complexity and timeout exit function in Oracle
Two methods of SSL certificate format conversion
隐藏在科技教育中的steam元素
Global and Chinese market of subscription revenue management software 2022-2028: Research Report on technology, participants, trends, market size and share
什么是证书透明度CT?如何查询CT logs证书日志?
2022 the action of protecting the net is imminent. Things about protecting the net
CMake教程系列-02-使用cmake代码生成二进制
CMake教程系列-05-选项及变量
How to switch ipykernel to a different CONDA virtual environment in jupyterlab?
在php中字符串的概念是什么
Welfare lottery | what are the highlights of open source enterprise monitoring zabbix6.0
SQLite use
怎么使用Vant实现数据分页和下拉加载
Heavy attack -- ue5's open source digital twin solution
What is certificate transparency CT? How to query CT logs certificate logs?
Azure 开发者新闻快讯丨开发者6月大事记一览
FDA ESG规定:必须使用数字证书保证通信安全
论文回顾:Playful Palette: An Interactive Parametric Color Mixer for Artists