-
There are several standard ways to cancel fetch request. This is quite useful for example when response takes too long to finish. There is AbortController or AbortSignal: timeout() None of these seems to work in SvelteKit within the same app. I thought SvelteKit tries to follow the standard Web APIs as much as possible https://svelte.dev/docs/kit/web-standards . My only workaround seems to be to move these endpoints a separate application API. Which seems quite a hassle. Am I missing something? |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 1 reply
-
It should work the exact same way as described in the MDN documentation you've linked. How are you trying to implement it now and in which file? |
Beta Was this translation helpful? Give feedback.
-
Yes @eltigerchino It should, but it does not. // routes/+page.svelte
Go to <a href="/roll">roll</a> // routes/roll/+page.svelte
<script>
let { data } = $props();
</script>
{data.number} // routes/roll/+page.server.js
export const load = async ({fetch}) => {
try {
let response = await fetch(
'api/longServerProcess' // internal api call will not be aborted
// "http://www.randomnumberapi.com/api/v1.0/randomnumber" //external api call will be aborted as expeted
, {
method: 'GET',
signal: AbortSignal.timeout(100),
headers: {
'Content-Type': 'application/json',
}
});
let number = await response.json()
return {number}
} catch (error) {
return {
serverTooSlow: true,
number: "api call interrupted cos server was too slow"
}
}
} // api/longServerProcess/+server.js
import { json } from '@sveltejs/kit';
const asyncTimeout = (ms) => {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
};
export async function GET() {
await asyncTimeout(5000)
const number = Math.floor(Math.random() * 100) + 1;
return json(number);
} My in real life app I solved this using a workaround. I have uploaded the api endpoint as a single app to Vercel and my app calls this app/endpoint. But it is annoying. |
Beta Was this translation helpful? Give feedback.
-
Following some test, not using SvelteKit fetch but the native one will cause AbortSignal.timeout(...) to abort internal api calls but wont respect the timeout value. The calls are aborted immediately. External api calls abortion works as expected even with native fetch. export const load = async () => {
try {
let response = await fetch(
'api/longServerProcess' // is aborted immediately instead of after 10000ms
// "http://www.randomnumberapi.com/api/v1.0/randomnumber" // works as expeted
, {
method: 'GET',
signal: AbortSignal.timeout(10000),
headers: {
'Content-Type': 'application/json',
}
});
let number = await response.json()
return {number}
} catch (error) {
return {
serverTooSlow: true,
number: "api call interrupted cos server was too slow"
}
}
} |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
As issue #13874 and PM #13877