我正在ES6中测试一个承诺驱动的生成器。基本上,生成器的每个产量都会返回一个承诺,一旦承诺得到解决,它就会恢复生成器。我的实现如下:
function* gen(x) {
try {
let result = yield pro(x);
console.log(`result is ${result}`);
let result1 = yield pro(result)
console.log(`result1 is ${result1}`);
} catch (e) {
console.log(`error ${e}`);
}
}
function pro(x) {
return new Promise((resolve, reject) => {
let rand = Math.random() * 100;
let res = rand * x;
setTimeout(() => { //simulate an async call
console.log(`rand: ${rand} ---- x: ${x}`);
resolve(res);
}, 1000);
});
}
function drive(generator) {
let args = Array.from(arguments).slice(1);
let it = generator.apply(this, args);
return Promise.resolve()
.then(function next(passedIn) {
let pVal = it.next(passedIn); //pass val to the generator
if (pVal.done) {
return pVal.value;
}
return Promise.resolve(pVal.value)
.then(next, (err) => {
it.throw(err);
});
})
.catch((err) => console.log(`error ${err}`));
}
drive(gen, 2);
上面的模式是否有任何弱点?感谢。