Skip to content

Instantly share code, notes, and snippets.

@miladvafaeifard
Created November 8, 2021 22:07
Show Gist options
  • Save miladvafaeifard/7fdf1ba7d8c01c8989957081fa76466b to your computer and use it in GitHub Desktop.
Save miladvafaeifard/7fdf1ba7d8c01c8989957081fa76466b to your computer and use it in GitHub Desktop.
How to cancel an HTTP request in Node.js
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();
}
}
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