Skip to content

Proposal: fetch with multiple AbortSignals #905

@jovdb

Description

@jovdb

I have some 'Higher Order functions' that can create me a fetch function with some extra behavior on it.

Some of them can abort the request.
Here a simplified example with a timeout that can abort:

const fetch = pipe(
  window.fetch,
  withTimeout({ timeoutInMs: 100 }), // 1 fetch can take max 100ms
  withRetry({ retryCount: 3, delayInMs: 100 }), // Retry 3x with a delay of 100ms
  withTimeout({ timeoutInMs: 400 }), // all fetches (with retry) can take max 400ms
)

In a real application, the second withTimeout could also be a withCancel function.

The first withTimeout will create an AbortController instance and set the signal property on the requestInit argument of fetch,
The second withTimeout will also create an AbortController and set the signal to the requestInit argument. This gives a problem because there already is a signal.

I could create for this sample one AbortController outside the withTimeout's and pass it to both withTimeout's as argument, but in a real application the enhancing of a fetch function can be done on different layers in the application. This causes other problems:

  • I must know if a parent layer already added abort behavior, if so I must pass the same abortController instance to withTimeout.
  • I must known which abortController instance is used for this fetch and have acces to it.

and this makes the code more dirty in my opinion.

What would be great is a way to pass multiple abort signals to a fetch function, some idea's:

  • let fetch also accept an array of abortSignals
  • provide a way to combine/merge two AbortSignal's into one AbortSignal

Here the example on CodePen

Metadata

Metadata

Assignees

No one assigned

    Labels

    addition/proposalNew features or enhancementsneeds implementer interestMoving the issue forward requires implementers to express interest

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions