DEV Community

Discussion on: Cancel fetch requests, and a way to abstract it

Collapse
 
loucyx profile image
Lou Cyx

If the problem is that you want to have a different instance of the AbortController every time you call fetch in the same endpoint, you could simply have a function like this:

/** @param {RequestInit} init */
const curriedFetch =
    init =>
    /** @param {RequestInfo} input */
    input =>
    /** @returns {[response: Promise<Response>, abort: AbortController['abort']]} */
    ({ signal, abort } = new AbortController()) =>
        [fetch(input, { signal, ...init }), abort];

const get = curriedFetch({ method: "GET" });
const fetchTodos = get("/todos");
const fetchUsers = get("/users");

const [todosRequest, abortTodosRequest] = fetchTodos();
const [usersRequest, abortUsersRequest] = fetchUsers();

todosRequest.then(console.log).catch(console.error); // Regular promise
abortTodosRequest(); // Aborts `fetchTodos`
Enter fullscreen mode Exit fullscreen mode

Is basically a curried version of fetch that returns a tuple with the response and the abort function, every time you call it you get a new AbortController.

Cheers!

Collapse
 
nombrekeff profile image
Keff

Interesting solution, no need to create custom promise here. I went the custom promise route because I was approaching it in an object-oriented way for another post.