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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.