【问题标题】:non recursive async implementation with generators使用生成器的非递归异步实现
【发布时间】:2021-11-28 20:03:55
【问题描述】:

我正在研究 javascript 生成器,我发现这个实现使用递归函数来模拟 async-await 的效果。我想知道我们是否可以实现类似但非递归的东西?我坚持了很长时间,但无法找到可行的解决方案。

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

【问题讨论】:

标签: javascript async-await promise generator


【解决方案1】:

不,您不能反复执行此操作。

请注意,“递归”调用实际上并不是递归的,而是异步的 .then() 回调再次调用该函数 - 并且该回调不是由函数直接调用,而是由 Promise 安排的。调用堆栈没有增长。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-07
    • 2019-05-19
    • 2021-07-11
    • 2019-08-03
    • 1970-01-01
    • 2010-11-19
    • 2014-08-19
    • 2018-08-05
    相关资源
    最近更新 更多