I have 2 questions to ask, regarding generators, since I am just learing this feature.
- Not sure, what is wrong in the below implementation. I was expenting the output to be
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
CODE :
function *generator(){
const res = yield fetch('https://jsonplaceholder.typicode.com/todos/1');
const response = yield res.json();
}
let g = generator();
g.next();
//PRINTS
> {value: Promise, done: false} //why the value here is Promise, I was expecting the json object
Please help me in understanding, what is wrong in the above code.
- My second question is, I am not understanding, or getting idea about the use cases of the generator, I mean, where we can use this kind of pausable functions in real projects.
A generator will return whatever you're returning after a
yield. In your case you are returning a promise, because that's what you're returning after the first yield.Another call to
nextshould return your result.One use case of a generator would be to generate an infinite list for instance. You cannot store it, but you can generate one element at a time and, most likely, stop at some point.
In general a generator is very useful when you don't want, or you can't, generate a full list of object and you do it one element at a time.