DEV Community

Cover image for Alternative to AbortController for Handling Async Timeouts in JavaScript
Varun Kelkar
Varun Kelkar

Posted on

Alternative to AbortController for Handling Async Timeouts in JavaScript

In the world of asynchronous JavaScript, understanding how to handle timeouts and cancellations isn’t just about tools like AbortController — it’s about crafting resilient and adaptable solutions for every scenario.

The AbortController API has become a go-to solution for handling task cancellations, especially in modern projects. However, it’s not always the ideal choice—or even an available one—depending on the context or the environment you're working in.

In this blog, we’ll explore alternative method for managing async timeouts without relying on AbortController.


async function customAbortController(asyncFunction, timeout = 5000) {
  return async (...args) => {
    const timeoutPromise = new Promise((_, reject) => {
      const id = setTimeout(() => {
        clearTimeout(id)
        reject(new Error(`Operation timed out after ${timeout} ms`))
      }, timeout)
    })
    try {
      return await Promise.race([asyncFunction(...args), timeoutPromise])
    } catch (error) {
      throw error
    }
  }
}

const abortControllerWrapper = async (asyncFunction, params) => {
  const response = await customAbortController(asyncFunction, 5000)
  return response(params);
}

// Example usage
const getUsers = async () => {
  const response = await fetch('https://jsonplaceholder.typicode.com/users')
  // handle response the way you prefer.
}

const getTodoById = async (id) => {
  const response = await fetch(`https://jsonplaceholder.typicode.com/todos/${id}`)
  // handle response the way you prefer.
}

const loadUsers = async () => {
  try {
    const response = await abortControllerWrapper(getUsers);
    // handle response the way you prefer.
  } catch (error) {
    console.error("ERROR", error.message) // "Operation timed out after 5000 ms"
  }
}
loadUsers();

// Try out yourself for getTodoById 😄

Enter fullscreen mode Exit fullscreen mode

What are we doing exactly?

In Javascript, Promise does not have any official way to cancel itself.

So we’re leveraging Promise.race() method here.

We’re creating a dummy Promise which resolves in given time & racing it against actual API call so either we get the API response or promise rejects after timeout has been crossed.

I hope this code was helpful 😄!

Feel free to customise according to your need & do let me know how did you feel about it ❤️

Top comments (0)