Created
November 8, 2021 22:07
-
-
Save miladvafaeifard/7fdf1ba7d8c01c8989957081fa76466b to your computer and use it in GitHub Desktop.
How to cancel an HTTP request in Node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fetch from 'node-fetch'; | |
import { setTimeout } from "node:timers/promises"; | |
const cancelRequest = new AbortController(); | |
const cancelTimeout = new AbortController(); | |
export async function timeout(delay) { | |
try { | |
await setTimeout(delay, undefined, { signal: cancelTimeout.signal }); | |
cancelRequest.abort(); | |
} catch (error) { | |
return; | |
} | |
throw new Error(`Request aborted as it took longer than ${delay}ms`); | |
} | |
export async function makeRequest(url) { | |
try { | |
const response = await fetch(url, { signal: cancelRequest.signal }); | |
return await response.json(); | |
} finally { | |
cancelTimeout.abort(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { makeRequest, timeout } from './helpers.js'; | |
const url = 'https://jsonplaceholder.typicode.com/todos/1'; | |
const result = await Promise.race([ | |
makeRequest(url), | |
timeout(100) | |
]); | |
console.log({ result }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment