Javascript - 使用生成器而不是承诺

Javascript - Using generators instead of promises

假设我有以下功能:

var f1 = function() {
    console.log('running f1');
    return new Promise(function(res, rej) {
        setTimeout(() => res('resolved_1!'), 1000);
    });
};

var f2 = function(a) {
    console.log('running f2 with ' + a);
    return new Promise(function(res, rej) {
        setTimeout(() => res('resolved_2!'), 2000);
    });
};

var f3 = function() {
    console.log('running f3');
    return new Promise(function(res, rej) {
        setTimeout(() => res('resolved_3!'), 3000);
    });
};

我可以 运行 他们:

let t1 = +new Date;
Promise.all([
    f1().then(a => {
        return f2(a);
    }),
    f3()
]).then((result) => {
    let t2 = +new Date;
    console.log(t2 - t1);
});

大约需要 3 秒。

现在我想运行这些函数使用生成器:

let t1 = +new Date;
let result = yield [f1(), f3()];
yield f2(result[0]);
let t2 = +new Date;
console.log(t2 - t1)

因为我需要 f1 的解析值来调用 f2,所以我将等待 f1 完成。这需要 5 秒。如何使用生成器获得相同的 3 秒?

This takes 5 seconds.

Slowdown due to non-parallel awaiting of promises in async generators

How can I get the same 3 seconds but using generators?

你只需要表达相同的控制流程:

let t1 = +new Date;
let result = yield [f1().then(f2), f3()];
let t2 = +new Date;
console.log(t2 - t1)

如果你出于某种原因想避免then,而是使用生成器,那必须是

let t1 = +new Date;
let result = yield [co(function*() {
    var a = yield f1();
    return yield f2(a); // yield is optional here
}), f3()];
let t2 = +new Date;
console.log(t2 - t1)