Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
fetch fire and forget in nodejs (I suppose it works in the browser as well)
import http from 'http';
import https from 'https';
import fetch, { Response } from 'node-fetch';
import { AbortController } from 'abort-controller';
const DEFAULT_TIMEOUT = 10000;
const httpAgent = new http.Agent({
keepAlive: true,
});
const httpsAgent = new https.Agent({
keepAlive: true,
});
function agent(u: any) {
if (u.protocol === 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
function fetchFireAndForget(url: string, options: any = {}): Promise<Response> {
const controller = new AbortController();
function anyhow(res: Response) {
let error = undefined;
if (!res.status || (res.status < 200 && res.status > 299)) {
error = res.status ? res.status : res
}
controller.abort();
return {
error,
status: res.status,
headers: res && res.headers,
};
}
return fetch(url, { agent, timeout: DEFAULT_TIMEOUT, signal: controller.signal, ...options })
.then(anyhow, anyhow);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment