Home > Web Front-end > JS Tutorial > Alternative to AbortController for Handling Async Timeouts in JavaScript

Alternative to AbortController for Handling Async Timeouts in JavaScript

Linda Hamilton
Release: 2024-12-07 09:42:12
Original
947 people have browsed it

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 ?

Copy after login

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 ❤️

The above is the detailed content of Alternative to AbortController for Handling Async Timeouts in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template