Tengo un código de espera de búsqueda de API que obtiene una lista de nodos en una matriz. El problema es que algunos de los nodos no responden por alguna razón (estar fuera de línea, puerto incorrecto, estar programado para NO responder, ...) y mi código está atascado esperando una respuesta de ese nodo.
¿Hay alguna forma de dejar de esperar una búsqueda, por ejemplo, después de 3 segundos si no llega ninguna respuesta?
Intenté usar try and catch, pero los nodos que no responden no devuelven nada, el código simplemente está ahí sin error ni respuesta.
¡¡Gracias!!
// 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); } )prueba esto
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; }y use esta función en su función fetchNodes
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"); } }