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

91
Views
async/await no espera antes de ejecutar la siguiente línea en JS

Encontré una función de retroceso exponencial que se supone que vuelve a intentar una búsqueda de API en caso de un error en los retrasos exponenciales:

 async function exponentialBackoff(toTry, max, delay) { console.log('max', max, 'next delay', delay); try { let response = await toTry() return response; } catch (e) { if (max > 0) { setTimeout(function () { exponentialBackoff(toTry, --max, delay * 2); }, delay); } else { console.log('maximum amount of tries exceeded', e); return e; } } }

Luego uso la función con la ayuda de la biblioteca API de GA para realizar una solicitud. A propósito, estoy enviando un cuerpo no válido para que la solicitud falle:

 response = await exponentialBackoff(async function () { return await gapi.client.request({ path: 'https://analyticsadmin.googleapis.com/v1beta/properties', method: 'POST', body: property }) }, 10, 30) console.log("NEXT LINE");

Lo que esperaría es que el retroceso exponencial se agotara en todos los intentos (10) y solo después de eso ejecutaría el registro de la consola.

Lo que realmente sucede es que el registro de la consola se ejecuta justo después del primer intento. ¿Qué estoy haciendo mal allí?

Gracias

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

  1. Promete setTimeout y await . Una variante prometida es

     function sleep(ms) { return new Promise(res => { setTimeout(res, ms); }); }
  2. await exponentialBackoff en el bloque catch .

El código fijo es:

 function sleep(ms) { return new Promise(res => { setTimeout(res, ms); }); } async function exponentialBackoff(toTry, max, delay) { console.log('max', max, 'next delay', delay); try { let response = await toTry() return response; } catch (e) { if (max > 0) { await sleep(delay); return await exponentialBackoff(toTry, --max, delay * 2); } else { console.log('maximum amount of tries exceeded', e); return e; } } }
about 4 years ago · Santiago Trujillo 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!