Back to all questions

What is AbortController?

Devs Hive

Devs Hive

Seen on interview: 0 users

AbortController is a controller that lets you cancel one or more asynchronous operations, as long as those operations support AbortSignal. It creates a signal object that you pass into the operation, and then at the right moment you call controller.abort() and the operation receives a signal to stop.

The best way to understand it is to look at an example with fetch. Imagine we have a React app, and one page makes a request that can take a long time. If the user leaves the page, the request will still complete and may break the UI.

This is a common problem in React, where state gets updated after the component has unmounted, and AbortController solves it nicely. In the example below, we create a controller and pass it to fetch. This way, we take control over the execution and can cancel it whenever we need.

If the user has left the page and the component has been removed from DOM, there is no point in continuing to execute HTTP-запиту, so we cancel it via controller.abort() before the component is removed from the tree.

useEffect(() => {
const controller = new AbortController();

(async () => {
const res = await fetch(`/api/users/${id}`, { signal: controller.signal });
setUser(await res.json());
})();

return () => controller.abort();
}, [id]);

If you want to learn more about everything AbortController can do, the best way is to read the documentation.

Before AbortController, there was another question on this topic. It went like this: Can a Promise be cancelled?

It was most often asked at Angular-інтервʼю, and the interviewer expected the developer to understand that a Promise cannot be cancelled and that Observable is needed to control the execution.

Seen on interview?

Comments (0)

Sign in to leave a comment

No comments yet. Be the first!