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

103
Vistas
non recursive async implementation with generators

I was studying javascript generators, and I found this implementation that simulates the effect of async-await using a recursive function. I was wondering if we can implement something similar, but non-recursive? I tought for a long time but couldn't get to a working solution.

function sum(...args) {
    let total = 0;
    return new Promise(function (resolve, reject) {
        setTimeout(function () {
            for (const arg of args) {
                if (typeof arg !== 'number') {
                    reject(`Invalid argument: ${arg}`);
                }
                total += arg;
            }
            resolve(total);
        }, 500);
    });
}

function recursiveAsync(gen, result) {
    const obj = gen.next(result);
    if (obj.done) return;
    obj.value.then(function (result) {
        recursiveAsync(gen, result);
    });
}

function async(genFn) {
    const gen = genFn();
    recursiveAsync(gen);
}

async(function* () {
    const a = yield sum(1, 3, 5);
    console.log(a);
    const b = yield sum(2, 4);
    console.log(b);
    const result = yield sum(a, b);
    console.log(result);
});
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

No, you cannot do that iteratively.

Notice that the "recursive" call is not actually recursive, rather it's the asynchronous .then() callback calling the function again - and that callback is not directly called by the function, it's scheduled by the promise. The call stack is not growing.

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