cj-2307
cj-2307

Reputation: 311

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

Upvotes: 0

Views: 97

Answers (1)

Bergi
Bergi

Reputation: 664548

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.

Upvotes: 1

Related Questions