From 82e003f7f59f48ed7a24bcb8e2e8bc148ddee5c7 Mon Sep 17 00:00:00 2001 From: Nolan Lawson Date: Sun, 11 Feb 2018 10:49:32 -0800 Subject: [PATCH] add timeout of 15 secs to all fetch requests --- routes/_utils/ajax.js | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/routes/_utils/ajax.js b/routes/_utils/ajax.js index 4c8e264..a081d46 100644 --- a/routes/_utils/ajax.js +++ b/routes/_utils/ajax.js @@ -1,5 +1,16 @@ +const TIMEOUT = 15000 + +function fetchWithTimeout(url, options) { + return Promise.race([ + fetch(url, options), + new Promise((resolve, reject) => { + setTimeout(() => reject(new Error(`Timed out after ${TIMEOUT / 1000} seconds`)), TIMEOUT) + }) + ]) +} + export async function post (url, body) { - return (await fetch(url, { + return (await fetchWithTimeout(url, { method: 'POST', headers: { 'Accept': 'application/json', @@ -18,7 +29,7 @@ export function paramsString (paramsObject) { } export async function get (url, headers = {}) { - return (await fetch(url, { + return (await fetchWithTimeout(url, { method: 'GET', headers: Object.assign(headers, { 'Accept': 'application/json'