Note we yield the result reference to JCcall()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
function JCcall() { return { horseInfoUrl: "hahah" } } function* foo(index) { yield index; // 0 const result = JCcall(); yield result; // > Object { horseInfoUrl: "hahah" } // note that since we yield result, our generator reference is on result now. const { horseInfoUrl } = result; console.log(`--> ${horseInfoUrl} --`); yield horseInfoUrl; // "hahah" } const iterator = foo(0); console.log('--- 1 ---') console.log(iterator.next().value); console.log('--- 2 ---') console.log(iterator.next().value); console.log('--- 3 ---') console.log(iterator.next().value); |
Note that we now move yield to JCcall instead.
1 2 3 4 5 6 7 8 |
yield index; // 0 const result = yield JCcall(); // now yield has moved your generator reference to the returned value of JCcall. // but since we did not capture it when JCcall returned, further iterator.next() will be gone and you'll get a // Error: Cannot destructure property 'horseInfoUrl' of 'result' as it is undefined. const { horseInfoUrl } = result; console.log(`--> ${horseInfoUrl} --`); yield horseInfoUrl; |
Another example is that we return another generator (* function) inside of our original generator function.
The yield* expression ( as opposed to the yield of a normal function above ) is used to delegate to another generator or iterable object.
1 2 3 4 5 6 7 8 |
function * anotherGenerator(i) { yield i + 1; yield i + 2; yield i + 3; return { horseUrl: "haah" } } |
The key point here is that we must put yield* in front like this:
1 2 3 4 5 |
function * generator(i) { const { horseUrl } = yield* anotherGenerator(i); console.log(horseUrl); // "haah" yield i; } |
Now, let’s run our generator.
1 2 3 4 5 6 7 |
var gen = generator(1); console.log(gen.next().value); // 2 console.log(gen.next().value); // 3 console.log(gen.next().value); // 4 console.log(gen.next().value); // undefined |