Skip to content

Instantly share code, notes, and snippets.

@simonplend
Last active September 2, 2021 08:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simonplend/11140141ea322f3f5c64bd8910c3717d to your computer and use it in GitHub Desktop.
Save simonplend/11140141ea322f3f5c64bd8910c3717d to your computer and use it in GitHub Desktop.
Example of using AbortController and AbortSignal with node-fetch
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