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

102
Vistas
async/await doesn't wait before executing next line in JS

I found an exponential backoff function which is supossed to retry an API fetch in case of an error in exponential delays:

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;
        }
    }
}

I then use the function with the help of GA API library to make a request. On purpose I am sending an invalid body to make the request fail:

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"); 

What I would expect is that the exponential backoff will run out of all attempts (10) and only after that it would execute the console log.

What actually happens is that the console log gets executed right after first try. What am I doing wrong there?

Thank you

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

  1. Promisify setTimeout and await it. A promisified variant is

    function sleep(ms) { return new Promise(res => { setTimeout(res, ms); }); }
    
  2. await exponentialBackoff in the catch block.

The fixed code is:

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 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