۱۳ آوریل ۲۰۲۲
این محتوا تنها در این زبان‌ها موجود است: English, Español, Français, Indonesia, Italiano, 日本語, 한국어, Русский, Türkçe, Українська, Oʻzbek, 简体中文. لطفاً به ما

Fetch: Abort

As we know, fetch returns a promise. And JavaScript generally has no concept of “aborting” a promise. So how can we cancel an ongoing fetch? E.g. if the user actions on our site indicate that the fetch isn’t needed any more.

There’s a special built-in object for such purposes: AbortController. It can be used to abort not only fetch, but other asynchronous tasks as well.

The usage is very straightforward:

The AbortController object

Create a controller:

let controller = new AbortController();

A controller is an extremely simple object.

  • It has a single method abort(),
  • And a single property signal that allows to set event listeners on it.

When abort() is called:

  • controller.signal emits the "abort" event.
  • controller.signal.aborted property becomes true.

Generally, we have two parties in the process:

  1. The one that performs a cancelable operation, it sets a listener on controller.signal.
  2. The one that cancels: it calls controller.abort() when needed.

Here’s the full example (without fetch yet):