logo
  • 現在做什麼
  • 關於我

Kalan

文章分類

  • 前端
  • 開發筆記
  • 雜談
  • 年度回顧

快速連結

  • 現在做什麼
  • 關於我
  • 聯絡我
  • 職涯思考🔗

關注我

在福岡生活的開發者,分享軟體開發與日本生活的點點滴滴。

© 2025 Kalan Made with ❤️. All rights reserved.

New way to cancel requests - AbortController

Written byKalanKalanJan 21, 2019
Home/Frontend
💡

If you have any questions or feedback, pleasefill out this form

Japanese原文

Table of Contents

    This post is translated by ChatGPT and originally written in Mandarin, so there may be some inaccuracies or mistakes.

    In the frontend, we primarily have two ways to send requests: XHR and Fetch. XHR has been around for, well... a long time. However, due to its complicated setup, it's often wrapped into higher-level APIs for easier use, such as jQuery's getJSON, axios, and RxJS's AjaxObservable, among others.

    In recent years, with the rising popularity of Promises, the Fetch API has significantly improved these issues. Besides returning a Promise for easy handling, the API is also quite straightforward.

    However, despite these advantages, there is still a critical drawback. Fetch cannot cancel requests. While we can use a setTimeout approach to ignore the returned value, the request will still continue to wait. In XHR, we can use XMLHttpRequest.abort to cancel requests, but there is no similar API in Fetch.

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

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

    Using it is quite simple:

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

    Then just pass the signal into fetch.

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

    When you call abortController.abort, it will send the signal to the fetch. If the request has not completed when the signal is received, the request will be canceled.

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

    If the request has not completed within five seconds, it will be canceled.


    Wrapping it with RxJS might make the entire API even more convenient to use. However, the current browser support is still not very good.

    ← Dealings with cookies with CORSRemember a debug process — connection →

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

    ☕Buy me a coffee