Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
Omisión de JavaScript en espera en recuperación pendiente

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); } )
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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"); } }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!