Kalan's Blog

Software Engineer / Taiwanese / Life in Fukuoka

Current Theme light

In the frontend, we mainly have two ways to send requests: XHR and Fetch. XHR is an API that has been around for a long time. However, due to its complicated configuration, it is often wrapped into higher-level APIs like jQuery's getJSON, axios, RxJS's AjaxObservable, etc.

In recent years, with the increasing popularity of Promises, the Fetch API has greatly improved these issues. Apart from returning a Promise for easy handling, the API itself is also quite simple.

However, despite these advantages, there is still one fatal drawback. Fetch cannot cancel requests. Although we can ignore the returned value using setTimeout, the request still continues to wait. In XHR, we can use XMLHttpRequest.abort to cancel the request, but there is no similar API in fetch.

Until recently! A new savior has finally emerged: AbortController.

The abort() method of the AbortController interface aborts a DOM request (e.g., a Fetch request) before it has completed. This is able to abort fetch requests, consumption of any response Body, and streams.

It's very simple to use.

const abortController = new AbortController()
const signal = abortController.signal

Then pass signal into fetch.

fetch("/long-running", { signal: signal })

When you call abortController.abort, it will be passed to fetch through the signal. If the request hasn't completed when the signal is received, the request will be canceled.

fetch("/long-running", { signal: signal })
setTimeout(() => abortController.abort(), 5000)

If the request hasn't completed within five seconds, it will be canceled.


Pairing it with RxJS can make the entire API more convenient to use. However, the current browser support is not very good.

Prev

Dealings with cookies with CORS

Next

Remember a debug process — connection

If you found this article helpful, please consider buy me a drink ☕️ It'll make my ordinary day shine✨

Buy me a coffee

作者

Kalan 頭像照片,在淡水拍攝,淺藍背景

愷開 | Kalan

Hi, I'm Kai. I'm Taiwanese and moved to Japan in 2019 for work. Currently settled in Fukuoka. In addition to being familiar with frontend development, I also have experience in IoT, app development, backend, and electronics. Recently, I started playing electric guitar! Feel free to contact me via email for consultations or collaborations or music! I hope to connect with more people through this blog.