When using yield in a generator, it does not always wait until a promise is fulfilled.
In order to make the example work, you need to write code that invokes the next method of an object implementing the iterable protocol.
function runGenerator(asyncGen) {
const gen = asyncGen();
let returnValue;
(function iterate(value){
returnValue = gen.next(value);
if(!returnValue.done) {
returnValue.value.then(iterate);
}
})();
}
const object = {
getPastEvents: () => Promise.resolve([1,2,3])
};
runGenerator(function*() {
const values = yield object.getPastEvents();
console.log(values);
});
Please note that this is a basic implementation and more conditions should be checked for use in actual projects.
Instead of creating your own implementation, consider using the co module.
It's important to know that Async & Await follows a similar approach, both requiring promisified APIs.
For Async & Await to work, ensure your JavaScript engine supports it, or transpile the code to work on older engines.
Generators will work on most modern JavaScript engines, as it is based on an older specification (ES6).
Transpiling Async & Await can lead to larger code size, which may impact content optimization goals.
A key difference between ES6 Generators and ES7 Async & Await is that ES6 Generators cannot use Arrow functions, which may be crucial in certain situations (as you need to store the "this" reference before entering the generator context), whereas ES7 Async Functions can utilize them.
Note that while ES7 Async & Await is syntactic sugar for promises, ES6 generators are not.