0

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);
});
cj-2307
  • 259
  • 3
  • 14
  • possible duplicate of https://stackoverflow.com/questions/36361827/non-recursive-method-to-iterate-over-promise-iterator/36454474#36454474 – Bergi Oct 09 '21 at 02:21

1 Answers1

1

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375