0
const f = n => new Promise((resolve, reject) => {
    setTimeout(()=>{
        if (n > 2){
            resolve({result: `${n} is higher than 2`});
        } else {
            resolve({error: `${n} is lower than 2`});
        }
    }, 1000);
});
function *m(){
    const {result, error} = yield f(parseInt(process.argv[2]));
    if(error){
        console.log(error);
    } else {
        console.log(result);
    }
}
m();

I'm using node.js v6.2 and when I execute node file.js 344 there is no result. If I put a debugger inside whatever function I choose, it doesn't stop while in debug mode.

It only stops if I extract the iterator with const it = m(); But I've seen examples where the above pattern seems to be correct. What am I missing? Thank you.

jgldev
  • 191
  • 11
  • Are the smart quotes intended? – Stephen Quan Jun 05 '16 at 12:34
  • You yield the promise, but don't do anything with it. Don't you need a corountine environment to achieve this? – Kyll Jun 05 '16 at 12:34
  • I think a promise should be only returned from a function and only while using the word "return". Try something like `n() return New Promise((resolve, reject)` – Roysh Jun 05 '16 at 12:43

1 Answers1

3

When you call m() you are initialising the generator but not doing anything with it. For the yield to happen you need to call next() on the result of m().

i.e

let generator = m()
generator.next().value.then(result => console.log(result)) 

// will log { result: '344 is higher than 2' } to the console

When you call next execution of the generator will resume and it will suspend when it encounters a yield. In this case the yield returns a promise, which will be available in the value property of the result of next.

https://davidwalsh.name/async-generators is a good read on the subject.