当前位置:网站首页>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
边栏推荐
猜你喜欢

The stacks 2022:32 marketing technology stacks selected

1、对范数的理解

深入理解ELF文件

喜报|海泰方圆通过CMMI-3资质认证,研发能力获国际认可
Qinheng ch583 USB custom hid debugging record

微博评论的计算架构

Chapter 4:win10 installing mingw64

Wechat applet reports an error: request:fail URL not in domain list

Deep understanding of ELF files

Utilisation de diskgenius pour augmenter la capacité du disque système C
随机推荐
Py3.6 and py3.7 installed by CONDA
哈希竞猜游戏系统开发如何开发?哈希竞猜游戏系统开发应用详情案例及源码
什么是算子?
How to judge whether you are suitable for software testing
Sentinel sentinel mechanism
图标丢失,URL附带JESSSIONID的什么来的?
new TypeReference用法 fastjson[通俗易懂]
Acy100 oil fume concentration online monitor for kitchen oil fume emission in catering industry
20 provinces and cities announce the road map of the meta universe
How to open a stock account is it safe to open an account
观察者模式之通用消息发布与订阅
解决nvprof 报错ERR_NVGPUCTRPERM - The user does not have permission to profile on the target device.
什么是泛型以及在集合中泛型的使用[通俗易懂]
VSCode /**生成函数注释
SQL Server实时备份库要求
Bilstm and CRF
Deeply understand and grasp the basic characteristics of digital economy
bert之我的小总结
OSError: Unable to open file (truncated file: eof = 254803968, sblock->base_addr = 0, stored_eof = 2
微服务介绍