当前位置:网站首页>Use of abortcontroller
Use of abortcontroller
2022-06-27 14:44:00 【flytam】
Today I will introduce a useful JavaScript api AbortController
AbortController What is it?
AbortController Interface represents a controller object , Allows you to abort one or more as needed Web request . You can use AbortController.AbortController() Constructor creates a new AbortController. Use AbortSignal Objects can be completed with DOM Requested communication
This api Simply put, it can provide us with the ability to terminate a fetch request
A termination fetch Requested demo as follows :
fetchButton.onclick = async () => {
const controller = new AbortController();
// Click on abort button Implementation termination fetch request
abortButton.onclick = () => controller.abort();
try {
const r = await fetch('/json', { signal: controller.signal });
const json = await r.json();
} catch (e) {
// If fetch If the request is terminated, an AbortError Error of
const isUserAbort = (e.name === 'AbortError');
}
};After early termination, this request is made in network In the panel status Is shown as canceled
In the absence of AbortController This api Before , We can't let the browser terminate a request in advance . And with this api after , The browser can terminate the request in advance, thus saving some user bandwidth . besides , This api It can also bring us some new development models
Controller and Signal
The following instantiates a AbortController, its signal Attribute is a AbortSignal
const controller = new AbortController();
const { signal } = controller;- controller It can be done by
controller.abort()To terminate its correspondingsignal signalItself cannot be terminated directly . It can be passed to some function calls such as fetch Or directly monitorsignalThe state of change ( Can passsignal.abortedseesignalThe state of or monitoring itabortevent )
The actual use
Termination in normal objects
Some old DOM api It is not supported AbortSignal. for example WebScocket Only one is provided close Method to close when we don't need it . If you want to use AbortSignal Can be similar to the following packaging
function abortableSocket(url, signal) {
const w = new WebSocket(url);
if (signal.aborted) {
w.close(); // signal Close immediately after the termination websocket
}
signal.addEventListener('abort', () => w.close());
return w;
} This is also very simple to use , But it's important to note that if signal If it has been terminated, it will not trigger abort event , We need to make a judgment first signal Has terminated
Remove event monitoring
We often need to be in js In dealing with dom Monitoring and unloading of . However, the following example will not take effect when the event listening and unloading incoming functions are not the same reference
window.addEventListener('resize', () => doSomething());
// Will not enter into force
window.removeEventListener('resize', () => doSomething()); Therefore, we often need some additional code to maintain the consistency of the callback function reference . And with AbortSignal Then we can have a new way to realize
const controller = new AbortController();
const { signal } = controller;
window.addEventListener('resize', () => doSomething(), { signal });
controller.abort(); because addEventListener Can also receive signal Attribute . We only need to call controller.abort(), This controller Of signal The related event listener passed will be unloaded automatically
Constructor mode
stay JavaScript We may need to manage very complex lifecycles in objects , Such as WebSocket. We need to start and then execute a series of logic and then terminate . Maybe we will write the following code
const someObject = new SomeObject();
someObject.start();
// After performing some operations
someObject.stop(); It can also be done through AbortSignal To implement
const controller = new AbortController();
const { signal } = controller;
const someObject = new someObject(signal);
// After performing some operations
controller.abort();- This makes it very clear that this object can only be executed once , Only from the beginning to the end , But not vice versa . If you want to use it again after it is terminated, you need to create an object again
- You can share one in many places
signal. We don't need to hold multipleSomeObjectExample . Just callcontroller.abort(), theseSomeObjectAll instances of can be terminated - If
SomeObjectThere are also internal calls likefetchAnd so on api Just put thissignalKeep delivering , befetchCan also be terminated together
Here is an example . Shows two signal Usage of . Pass to built-in apifetch And inspection signal State to perform some actions
export class SomeObject {
constructor(signal) {
this.signal = signal;
// Perform some operations, such as sending a request
const p = fetch('/json', { signal });
}
doComplexOperation() {
if (this.signal.aborted) {
throw new Error(`thing stopped`);
}
for (let i = 0; i < 1_000_000; ++i) {
// Perform complex operations
}
}
}react hook Asynchronous calls in
We usually go to useEffect Some asynchronism in api call . With the help of signal Next time useEffect Call again api Will terminate the previous call
function FooComponent({ something }) {
useEffect(() => {
const controller = new AbortController();
const { signal } = controller;
const p = (async () => {
const j = await fetch(url + something, { signal });
})();
return () => controller.abort();
}, [something]);
return <>...<>;
} You can also encapsulate a useEffectAsync Of hook
function useEffectAsync(cb,dependence) {
const controller = new AbortController();
const { signal } = controller;
useEffect(() => {
cb(signal);
return () => controller.abort();
},dependence)
}Some useful AbortSignal Method
These methods may not be implemented yet
AbortSignal.timeout(ms): Create a that terminates after a given timeAbortSignal
function abortTimeout(ms) {
const controller = new AbortController();
setTimeout(() => controller.abort(), ms);
return controller.signal;
}AbortSignal.any(signals): Create aAbortSignal, If any of the incomingsignalIt's over , This one returnssignalIt will also be terminated
function abortAny(signals) {
const controller = new AbortController();
signals.forEach((signal) => {
if (signal.aborted) {
controller.abort();
} else {
signal.addEventListener('abort', () => controller.abort());
}
});
return controller.signal;
}AbortSignal.throwIfAborted(): IfsignalItself has ended , Calling this method will throw an executionabort(reason)When the specified reason abnormal ; Otherwise, it will be executed silently
if (signal.aborted) {
throw new Error(...);
}
// becomes
signal.throwIfAborted();This method is not easy at present polyfill, But it can be realized through the following tool functions
function throwIfSignalAborted(signal) {
if (signal.aborted) {
throw new Error(...);
}
}Reference resources
https://whistlr.info/2022/abortcontroller-is-your-friend/
边栏推荐
- 【每日3题(3)】盒子中小球的最大数量
- Gaode map IP positioning 2.0 backup
- Massive data! Second level analysis! Flink+doris build a real-time data warehouse scheme
- [OS command injection] common OS command execution functions and OS command injection utilization examples and range experiments - based on DVWA range
- Leetcode 724. 寻找数组的中心下标(可以,一次过)
- 【高等数学】从法向量到第二类曲面积分
- Daily 3 questions (1): find the nearest point with the same X or Y coordinate
- Debug tool
- 机械硬盘和ssd固态硬盘的原理对比分析
- [business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
猜你喜欢

Référence forte, faible, douce et virtuelle de threadlocal

CV领域一代宗师黄煦涛教授86岁冥诞,UIUC专设博士奖学金激励新锐

隱私計算FATE-離線預測

【OS命令注入】常见OS命令执行函数以及OS命令注入利用实例以及靶场实验—基于DVWA靶场

ReentrantLock、ReentrantReadWriteLock、StampedLock

Pycharm安装与设置

ThreadLocal之强、弱、軟、虛引用

LVI: feature extraction and sorting of lidar subsystem
![[business security-04] universal user name and universal password experiment](/img/09/73d8356d00cefb6d1af086669f69ff.png)
[business security-04] universal user name and universal password experiment

Array related knowledge
随机推荐
Resolve activity startup - lifecycle Perspective
my. INI file configuration
CCID Consulting released the database Market Research Report on key application fields during the "14th five year plan" (attached with download)
The global chip market may stagnate, and China's chip expansion accelerates to improve its self-sufficiency rate against the trend
[PHP code injection] common injectable functions of PHP language and utilization examples of PHP code injection vulnerabilities
易周金融 | Q1手机银行活跃用户规模6.5亿;理财子公司布局新兴领域
【mysql进阶】MTS主从同步原理及实操指南(七)
Debug tool
Great God developed the new H5 version of arXiv, saying goodbye to formula typography errors in one step, and the mobile phone can easily read literature
volatile与JMM
[business security 03] password retrieval business security and interface parameter account modification examples (based on the metinfov4.0 platform)
PR second training notes
Tsinghua & Shangtang & Shanghai AI & CUHK proposed Siamese image modeling, which has both linear probing and intensive prediction performance
Interview question: rendering 100000 data solutions
注解学习总结
enable_ if
Notes learning summary
LVI: feature extraction and sorting of lidar subsystem
Reflection learning summary
AutoCAD - line width setting