Last active
September 2, 2021 08:30
-
-
Save simonplend/11140141ea322f3f5c64bd8910c3717d to your computer and use it in GitHub Desktop.
Example of using AbortController and AbortSignal with node-fetch
This file contains hidden or 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 cancelTimeout = new AbortController(); | |
const cancelRequest = new AbortController(); | |
async function timeout(milliseconds) { | |
try { | |
await setTimeout(milliseconds, undefined, { signal: cancelTimeout.signal }); | |
cancelRequest.abort(); | |
} catch (error) { | |
// Ignore rejections | |
} | |
} | |
async function makeRequest() { | |
try { | |
const response = await fetch("http://localhost:3000/", { | |
signal: cancelRequest.signal, | |
}); | |
const responseData = await response.json(); | |
return responseData; | |
} catch (error) { | |
if (error.name === "AbortError") { | |
console.error("Request was aborted"); | |
} else { | |
console.error(error); | |
} | |
} finally { | |
cancelTimeout.abort(); | |
} | |
} | |
const result = await Promise.race([timeout(2000), makeRequest()]); | |
console.log({ result }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment