Kalan's Blog

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

四零二曜日電子報上線啦!訂閱訂起來

Software Engineer / Taiwanese / Life in Fukuoka
This blog supports RSS feed (all content), you can click RSS icon or setup through third-party service. If there are special styles such as code syntax in the technical article, it is still recommended to browse to the original website for the best experience.

Current Theme light

我會把一些不成文的筆記或是最近的生活雜感放在短筆記,如果有興趣的話可以來看看唷!

Please notice that currenly most of posts are translated by AI automatically and might contain lots of confusion. I'll gradually translate the post ASAP

New way to cancel requests - AbortController

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