AreWe

fetch timeout and abortion

Mar 21st, 2021 (edited)
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const networkCall = async ({ path = '', method = '', body = {} }) => {
  2.   const controller = new AbortController();
  3.   const { signal } = controller;
  4.   const req = { method, headers: { 'Content-Type': 'application/json' }, signal };
  5.  
  6.   if (method !== 'GET') {
  7.     req.body = JSON.stringify(body);
  8.   }
  9.  
  10.   const responseInfo = { done: false };
  11.   const response = await Promise.race([
  12.     fetch(path, req).then((res) => {
  13.       responseInfo.done = true;
  14.       return res.json();
  15.     }),
  16.     new Promise((resolve) => {
  17.       setTimeout(() => {
  18.         resolve({ error: `Bad connection ('${path}')` });
  19.         if (!responseInfo.done) {
  20.           controller.abort();
  21.         }
  22.       }, 15000);
  23.     }),
  24.   ]);
  25.  
  26.   return response;
  27. };
Add Comment
Please, Sign In to add comment