0

I have 2 questions to ask, regarding generators, since I am just learing this feature.

  1. 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.

  1. 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.
RONE
  • 5,415
  • 9
  • 42
  • 71

3 Answers3

1

You have to wait for the fetch to resolve first, you can do that with .then() or making the generator async and awaiting the fetch. Although, that wouldn't be much of use nowadays. Before async/await or even promises, people used generators like you would use async/await today with something like a co wrap, which was based on callbacks.

As for today's use of them, you can find them in libs such as redux-saga, but they were mostly replaced by async/await and promises, which are much more lightweight and easier to reason about.

Filip Kaštovský
  • 1,866
  • 8
  • 12
0

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 next should 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.

Radu Diță
  • 13,476
  • 2
  • 30
  • 34
0

try it:

async function* generator() {
    yield (await fetch('https://jsonplaceholder.typicode.com/todos/1'))
        .json()
}

(async () => console.log((await generator()).next()))()