3

I have an API fetch await code that fetches list of nodes in an array. The problem is, some of the nodes don't respond for whatever reason (being offline, wrong port, being programmed NOT to respond, ... ) and my code is stuck awaiting a reply from that node.

Is there any way to stop awaiting a fetch for example after 3 seconds if no response comes?

I tried using try and catch, but the nodes that don't respond don't return anything, the code is simply sitting there with no error or response.

Thank you!!

// list of nodes        
let nodes = [{
                "address": {
                    "hostname": "192.168.1.1",
                    "port": 31350
                }
            }, {
                "address": {
                    "hostname": "192.168.1.2",
                    "port": 31350
                }
            }
        ]
    
    
// api fetch function    
    async function fetchNodes(hostname, port) {
    
      const response = await fetch(`https://${hostname}:${port}/getstatus`, {
      method: 'post',
      body: JSON.stringify(body),
      headers: {'Content-Type': 'application/json'}
      });

      const data = response.json();   
      console.log(data);
    
    }
    
// loop to call api fetch function with all array entries       
    nodes.forEach(function(entry) {
     fetchNodes(entry.address.hostname, entry.address.port);
        }
    )
masch1na
  • 97
  • 5

1 Answers1

1

try this

 async function fetchWithTimeout(resource, options = {}) {
  const { timeout = 8000 } = options;
  
  const controller = new AbortController();
  const id = setTimeout(() => controller.abort(), timeout);
  const response = await fetch(resource, {
    ...options,
    signal: controller.signal  
  });
  clearTimeout(id);
  return response;
}

and use this function in you fetchNodes function

  async function fetchNodes() {
  try {
    const response = await fetchWithTimeout(
      `https://${hostname}:${port}/getstatus`,
      {
        timeout: 6000,
        method: "post",
        body: JSON.stringify(body),
        headers: { "Content-Type": "application/json" },
      }
    );
    const data = await response.json();
    return data;
  } catch (error) {
    // Timeouts if the request takes
    // longer than 6 seconds
    console.log(error.name === "AbortError");
  }
}