Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

143
Vistas
Espere hasta que se complete una operación externa con setInterval antes de finalizar

Obtuve un código JS que simplemente activa un método. Este método invoca una solicitud HTTP que está causando que comience algún proceso remoto. Luego, debo verificar cada 5 segundos si el proceso remoto finalizó con un tiempo de espera de 5 minutos, luego de lo cual debo detener la espera y generar un error si el tiempo de espera expiró; de lo contrario, simplemente necesito registrar el resultado y completar el método. .

Lo que no estoy seguro es cómo detengo la ejecución del método principal hasta que obtenga la respuesta para poder tener un valor para registrar. Esto es lo que tengo hasta ahora:

 (async function(param) { ... var res = await fetch(...); //activate the remote proccess var textAnswer = await res.text(); var infoObj = JSON.parse(textAnswer); startChecks(infoObj.info.id); // this is the method which I need to await on somehow }("paramValue"); async function startChecks(id) { var startTime = new Date().getTime(); intervalId = setInterval(checkStatus, 5000, id, startTime); } async function checkStatus(id, startTime) { //if more than 5 minutes had passed if(new Date().getTime() - startTime > 300000) { clearInterval(intervalId); throw new Error("External pipeline timeout expired"); } var res = await fetch(...); //check remote process var ans = await res.text(); var obj = JSON.parse(ans); if(obj.finished) clearInterval(intervalId); }

Como dije, lo que quiero lograr es que mi función principal no termine hasta que todos los intervalos terminen con el error arrojado o el proceso finalice. ¿Cómo puedo lograr eso?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Crearía una función de ayuda que ejecute su función en intervalos dados hasta que se resuelva en algo diferente a undefined . Pero solo por la cantidad máxima de tiempo.

Esto podría ser algo como esto:

 // helper to wait for time milliseconds async function sleep(time) { return new Promise(resolve => setTimeout(resolve, time)); } async function repeatedExecution(callback, interval, timeout) { // get start time const start = Date.now(); // repeat as long the start time + timout is larger then the current time while (start + timeout > Date.now()) { // get a promise that resolves in interval seconds let sleeper = sleep(interval) // execute the callback let res if (res = await callback()) { // if the callback returns something truthy return it return res; } // wait until time for interval ends and then continue the loop await sleeper; } // if we reach this point we timed out throw new Error('timed out'); } async function run() { /* var res = await fetch(...); //activate the remote proccess var textAnswer = await res.text(); var infoObj = JSON.parse(textAnswer); */ try { let result = await repeatedExecution(() => { /* var res = await fetch(...); //check remote process var ans = await res.text(); var obj = JSON.parse(ans); if(obj.finished) { return true } */ }, 1000, 3000); // do something on success } catch (err) { // handle the error (timeout case) console.error(err) } } run();

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda