I am testing a promise-driven generator in ES6. Basically, each yield of the generator returns a promise which resumes the generator once the promise is resolved. My implementation is below:
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);
Is there any weakness in the pattern above? thanks.