Skip to content

Tutorial: Cancelling a request that is ongoing

Taevas edited this page Apr 22, 2024 · 1 revision

Let's say you want to make a request that you can cancel at any time, how can you achieve that?

Firstly, it's important to know that this package uses fetch() (more specifically node-fetch for the time being) which accepts what's known as an AbortSignal The usual way to get an AbortSignal is to first create an AbortController to then get its signal:

const my_controller = new AbortController()
const my_signal = my_controller.signal

You've got yourself an AbortSignal! But how are you supposed to use it? If you look at, say, API.getUser(), you will see there's nowhere to give anything like that! That's because, if you're going to provide an AbortSignal, you're gonna need to provide it with a separate method right before doing your request!

The method in question is gonna be API.withSettings():

const user = await api.withSettings({signal: my_signal}).getUser(7276846)

Alternatively, if you're going to use the same signal for multiple requests, you might not want to write so much for each request, so instead you could do something more like that:

const special_api = api.withSettings({signal: my_signal})
const user_1 = await special_api.getUser(11409334)
const user_2 = await special_api.getUser(9676089)

All requests that are using that signal will be cancelled whenever you want! Although we haven't talked about how you can actually do that...

Alright, fret not, it's really simple! Do you remember my_controller from earlier, the one that was used to create my_signal? Turns out creating signals is not its only use! As it turns out, it also has a method called abort(), and that's exactly what you want to use!

The abort method of an AbortController will cancel any request that is using the AbortSignal of this very same AbortController:

my_controller.abort()

Do note that cancelling a request means making it throw an APIError, so make sure your application is able to handle that properly!

Clone this wiki locally