Aborting a fetch request ????

栏目: IT技术 · 发布时间: 4年前

内容简介:TLDR:As of today, there are two primary ways to make a request in the browser.

TLDR: AbortController is used to abort a fetch request..

As of today, there are two primary ways to make a request in the browser. XMLHttpRequest and fetch . XMLHttpRequest existed in browsers for a long time. the fetch was introduced with ES6 .

XMLHttpRequest was always abortable. An abortable XHR request looks something like this.

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 wasn’t abortable when it was initially introduced. the initial GitHub issue for aborting a fetch request was opened initially in 2015. There were also many attempts to solve this problem outside of the fetch spec like cancelable-promises and other hacks .

But, we now finally have the generic AbortController and the AbortSignal APIs. These APIs are provided by the DOM standard , not by the language itself.

What is an AbortController?

Aborting a fetch request ????
Abort controller in the devtool

As described in the DOM spec documentation

Though promises do not have a built-in aborting mechanism, many APIs using them require abort semantics. AbortController is meant to support these requirements by providing an abort() method that toggles the state of a corresponding AbortSignal object. The API which wishes to support aborting can accept an AbortSignal object, and use its state to determine how to proceed.

// Create a instance of the AbortController
const controller = new AbortController();
const signal = controller.signal;

// Listen for abort signal, callback executed on controller.abort()
signal.addEventListener('abort', () => {
  console.log(signal.aborted); // true
});

// Abort at a later stage, this will notify the signal
controller.abort();

How to abort fetch request using AbortController?

fetch accepts AbortSignal as part of the second argument.

const controller = new AbortController();
const signal = controller.signal;

// API responds after 5s
// Note the 'signal' in the second argument
fetch('https://slowmo.glitch.me/5000', { signal })
  .then(r => r.json())
  .then(response => console.log(response))
  .catch(err => {
    if (err.name === 'AbortError') {
      console.log('Fetch was aborted');
    } else {
      console.error('Oops!', err);
    }
  });


// Abort the request after 2s
// This will abort the fetch with 'AbortError'
setTimeout(() => {
  controller.abort();
}, 2000);

Aborting the fetch aborts both the request and response. The request fails with the error new DOMException('Aborted', 'AbortError') .

The same AbortSignal ( signal in the above example) can be used to abort multiple fetch requests.

Aborting a fetch request ????
Aborted fetch request in the devtool

Demo

AbortController is not only for fetch. it’s a generic API to abort asynchronous tasks. Eg: You can use it to implement a cancelable promise .

Browser support and polyfill

Aborting a fetch request ????

Many older browsers don’t support the AbortController and the AbortSignal APIs. You can use either of these polyfills to make it work.

https://www.npmjs.com/package/abort-controller https://www.npmjs.com/package/abortcontroller-polyfill

That’s it for now. If you enjoyed reading this post, give me a follow @ganapativs :grimacing:

References:

Thanks:


以上所述就是小编给大家介绍的《Aborting a fetch request ????》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

运营之光

运营之光

黄有璨 / 电子工业出版社 / 2016-9-1 / 59.00元

在互联网行业内,“运营”这个职能发展到一定阶段后,往往更需要有成熟的知识体系和工作方法来给予行业从业者们以指引。 《运营之光:我的互联网运营方法论与自白》尤其难得之处在于:它既对“什么是运营”这样的概念认知类问题进行了解读,又带有大量实际的工作技巧、工作思维和工作方法,还包含了很多对于运营的思考、宏观分析和建议,可谓内容完整而全面,同时书中加入了作者亲历的大量真实案例,让全书读起来深入浅出、......一起来看看 《运营之光》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具