简体   繁体   中英

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.

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. This takes 5 seconds. How can I get the same 3 seconds but using generators?

This takes 5 seconds.

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

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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