简体   繁体   English

Javascript-使用生成器代替Promise

[英]Javascript - Using generators instead of promises

suppose I have following functions: 假设我具有以下功能:

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

I can run them with: 我可以使用以下命令运行它们:

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

And it takes roughly 3 seconds. 大约需要3秒钟。

Now I want to run these functions using generators: 现在,我想使用生成器运行以下功能:

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

Since I need resolved value of f1 to call f2 I shall wait for f1 to complete. 由于我需要解析的f1值才能调用f2,因此我将等待f1完成。 This takes 5 seconds. 这需要5秒钟。 How can I get the same 3 seconds but using generators? 如何使用发电机使用相同的3秒时间?

This takes 5 seconds. 这需要5秒钟。

See Slowdown due to non-parallel awaiting of promises in async generators . 请参阅减速,因为异步生成器中没有并行等待诺言

How can I get the same 3 seconds but using generators? 如何使用发电机使用相同的3秒时间?

You just have to express the same control flow: 您只需要表达相同的控制流程:

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

If you want to avoid then for some reason, and use generators instead, it would have to be 如果你想避免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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM