当前位置:网站首页>Interrupt operation: abortcontroller learning notes
Interrupt operation: abortcontroller learning notes
2022-06-25 18:08:00 【Zhou Junjun blog】
Front end interview usually likes to ask :
- Please cancel the handwriting function with a delay ,axios What is the principle of the cancel function ?
- How to interrupt a request fetch Principle analysis and application of ?
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
https://caniuse.com/?search=AbortController
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 https://zhuanlan.zhihu.com/p/416572062
[ translate ] Use AbortController End fetch request https://juejin.cn/post/6844904072051425293
An interruptible request fetch Principle analysis and application of ( Previous notes ) https://github.com/ctq123/blogs/issues/9
AbortController Use scenarios to explore https://www.jianshu.com/p/2f23c33e1922
Reprint This station article 《 Interrupt operation :AbortController Learning notes 》, Please indicate the source :https://www.zhoulujun.cn/html/webfront/SGML/html5/2022_0530_8824.html
边栏推荐
猜你喜欢

New characteristics of cultural consumption in the era of digital economy

Bilstm and CRF

win10安装cuda的操作步骤(不断完美中)

利用Qt制作美化登录界面框

Optimization of lazyagg query rewriting in parsing data warehouse

Deeply understand and grasp the basic characteristics of digital economy

什么是算子?

A simple and easy-to-use graph visualization tool developed recently

【工作小技巧】刚入职的软件测试工程师怎么快速上手新岗位

What is an operator?
随机推荐
使用DiskGenius拓展系統盤C盤的容量
C语言中%含义
配电室环境的分布式远程管理
[compilation principle] lexical analysis
There is a repeating element iii[pruning with ordered ordering]
篇4:win10安装MingW64
Kotlin of Android cultivation manual - several ways to write a custom view
QT using SQLite database
Which of the top ten securities companies has the lowest commission? Is it safe to open an account
mysql mysql-8.0.19-winx64 安装与navicat连接
什么是算子?
ASP.NET超市便利店在线购物商城源码,针对周边配送系统
什么是泛型以及在集合中泛型的使用[通俗易懂]
[daily record] - bug encountered during BigDecimal Division
What is public chain development? What are the public chain development projects?
卷积操作的本质特性+TextCNN文本分类
How to open a stock account is it safe to open an account
RuntimeError: Trying to backward through the graph a second time (or directly access saved variable
new TypeReference用法 fastjson[通俗易懂]
conda安装的py3.6和py3.7