当前位置:网站首页>Use of abortcontroller
Use of abortcontroller
2022-06-26 15:26: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 terminatedIf
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/
边栏推荐
- [tcapulusdb knowledge base] tcapulusdb doc acceptance - transaction execution introduction
- clustermeet
- 5张图诠释了容器网络
- RestCloud ETL与Kettle对比分析
- Unity C # e-learning (10) -- unitywebrequest (1)
- Shell script multi process concurrent writing method example (high level cultivation)
- IDEA本地代理后,无法下载插件
- vue中缓存页面 keepAlive使用
- Restcloud ETL extracting dynamic library table data
- Evaluate:huggingface detailed introduction to the evaluation index module
猜你喜欢

English语法_形容词/副词3级 - 原级句型
![[CEPH] cephfs internal implementation (II): example -- undigested](/img/87/6eb214550faf1f0500565c1610ff3b.png)
[CEPH] cephfs internal implementation (II): example -- undigested
![[tcapulusdb knowledge base] Introduction to tcapulusdb general documents](/img/7b/8c4f1549054ee8c0184495d9e8e378.png)
[tcapulusdb knowledge base] Introduction to tcapulusdb general documents

设计人员拿到的工程坐标系等高线CAD图如何加载进图新地球

数据库-完整性约束

人力资源导出数据 excel VBA

【TcaplusDB知识库】TcaplusDB OMS业务人员权限介绍

Function: crypto JS encryption and decryption

【ceph】cephfs caps简介

【ceph】CephFS 内部实现(三):快照
随机推荐
[tcapulusdb knowledge base] Introduction to tcapulusdb data structure
学习内存屏障
Evaluate:huggingface detailed introduction to the evaluation index module
Learning memory barrier
SAP GUI 770 Download
R language uses ggplot2 to visualize the results of Poisson regression model and count results under different parameter combinations
Is it safe to open a new bond registration account? Is there any risk?
There are so many vulnerabilities in tcp/ip protocol?
设计人员拿到的工程坐标系等高线CAD图如何加载进图新地球
【C语言练习——打印空心上三角及其变形】
On which platform is it safe to buy shares and open an account? Ask for guidance
R language dplyr package summary_ The at function calculates the mean and median of multiple data columns (specified by vectors) in the dataframe data, and specifies na RM parameter configuration dele
Using restcloud ETL shell component to schedule dataX offline tasks
R language uses the aggregate function of epidisplay package to split numerical variables into different subsets based on factor variables, calculate the summary statistics of each subset, and use agg
/etc/profile、/etc/bashrc、~/. Bashrc differences
小程序:uniapp解决 vendor.js 体积过大的问题
English grammar_ Adjective / adverb Level 3 - original sentence pattern
[wechat applet] event binding, do you understand?
乐鑫 AWS IoT ExpressLink 模组达到通用可用性
Deployment of kubernetes' controller