0

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.

VietNg
  • 81
  • 1
  • 7
  • I see `try/catch` with asynchronous code and wonder if [this](https://stackoverflow.com/questions/19727905/in-javascript-is-it-expensive-to-use-try-catch-blocks-even-if-an-exception-is-n/19728357#19728357) answer about try/catch has any significance (the part about asynch code in a `try` block ... I admit however, I'm not sure if/how `yield` changes that comment – Jaromanda X Dec 08 '16 at 08:15
  • In a line: `const drive = (generator, it = generator()) => Promise.resolve().then(function next(prev, {done, value} = it.next(prev)) => done ? value : Promise.resolve(value).then(next, it.throw.bind(it)));` – Benjamin Gruenbaum Dec 08 '16 at 08:22
  • Thanks @JaromandaX for the useful links. Any issues related to promises and generators? – VietNg Dec 08 '16 at 08:24
  • nothing more than is available in http://stackoverflow.com/questions/33467441/how-to-combine-es6-generators-with-promises?rq=1 – Jaromanda X Dec 08 '16 at 08:28
  • @BenjaminGruenbaum nice code! Is `it.throw.bind(it)` used to prevent throw to be executed immediately (returning a function instead)? If so, in a sense, would it be equivalent to `(err) => it.throw(err)`? cheers. – VietNg Dec 08 '16 at 08:30
  • @VietNg it returns a function with a fixed `this` value (sets it to `it`) and parameters (not used in this case). Also note I'm not catching the error (since that would mean instrumentation and consumers can't handle it). – Benjamin Gruenbaum Dec 08 '16 at 09:08

0 Answers0