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?